结果类型的初始值设定项失败?

Ant*_*ton 1 initializer resulttype swift failable

我有一个结构MyStruct。它可以从字符串初始化,但是有很多方法会导致字符串无效。我不想简单地创建一个在所有失败情况下init?(string: String)返回相同的可失败初始化程序nil,而是希望有一个返回 Result 类型的初始化程序,Result<MyStruct, Error>以便调用方法可以知道发生了哪种失败情况并报告信息性错误。

我可以写一个方法static func makeNew(string: String) -> Result<Self, Error>。这样就不用打电话了

guard let new = MyStruct(string: someString) else {
   print("\(someString) was invalid somehow.")
}
print("Object created.)
Run Code Online (Sandbox Code Playgroud)

我可以makeNew这样调用:

switch MyStruct.makeNew(string: someString) {
case .success(let new):
   print("Object created")
case .failure(let error):
   switch error {
      // handle each specific error appropriately
   }
}
Run Code Online (Sandbox Code Playgroud)

这是唯一的方法,还是 Swift 给了我们一个实际的初始化器来做到这一点?

Ale*_*ica 5

您可以throw从初始化程序中改为:

struct MyStruct {
    struct ValidationError: Error {} // Example error

    init(_ string: String) throws {
        guard isValid() else { throw ValidationError() }
        ...
    }
}

do {
    let new = try MyStruct("some string")
    print("Object created: \(new)")
} catch let e as MyStruct.ValidationError {
    // handle each specific error appropriately
} catch {
    print("Other unexpected error")
}
Run Code Online (Sandbox Code Playgroud)

返回标记的函数T(或 的初始化器Tthrows与返回标记的函数大致同构Result<T, any Error>