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
    }
}

 

posted @ 2018-03-06 10:10  ShellHan  阅读(428)  评论(0编辑  收藏  举报