zoukankan      html  css  js  c++  java
  • Swift-初始化失败处理方法

    1. 使用failable initializers

    /// using failable initializers
    //1. 返回可选类型值
    //2. 可以返回nil表示初始化失败
    struct StructA {
        var propertyA: Int
        
        init?(propertyA: Int) {
            if propertyA < 0 {
                return nil
            }
            self.propertyA = propertyA
        }
    }

    2.  抛出异常并处理

    /// throw from an initializer
    enum ErrorType: Error {
        case EmptyProperty
        case InvalidValue
    }
    
    struct StructB {
        var propertyA: String
        var propertyB: Int
        
        init(propertyA: String, propertyB: Int) throws{
            if propertyA.isEmpty {
                throw ErrorType.EmptyProperty
            }
            
            if propertyB < 0 {
                throw ErrorType.InvalidValue
            }
            
            self.propertyA = propertyA
            self.propertyB = propertyB
        }
    }
    
    do {
        let instance = try StructB(propertyA:"m", propertyB:-1)
    }catch let err{
        switch err {
        case ErrorType.EmptyProperty:
            print("Empty")
        case ErrorType.InvalidValue:
            print("Invalid")
        default:
            break
        }
    }
  • 相关阅读:
    单调栈模板
    Yet Another Broken Keyboard[双指针]
    经典递归集合
    [未完成]ECRound 80
    #614 C. NEKO's Maze Game[简易DFS,0|1转换]
    等差数列异或和模板
    线段树基础题
    前缀和&差分
    优先队列
    st表模板
  • 原文地址:https://www.cnblogs.com/HackHer/p/8512770.html
Copyright © 2011-2022 走看看