ios - 作为构造函数关闭?

标签 ios swift

我在 objc io 书中看到过这样的示例

callback(Result {
    if let e = error {
       throw e
    }

    guard let d = data else {
       throw NoDataError()
    }

    return try JSONDecoder().decode(User.self, from: d)
})

回调在哪里

“callback: @escaping (Result<User, Error>) -> ()

似乎 Result(Swift 定义的枚举类型)正在使用闭包来创建自身?

但我没有看到任何相关文档

最佳答案

有文档。

该表达式表示 init(catching:) 的尾随闭包语法方法Result 。说明是

Creates a new result by evaluating a throwing closure, capturing the returned value as a success, or any thrown error as a failure.

完整的语法是

callback(Result(catching: {
    if let e = error { 
       throw e 
    }

    guard let d = data else { 
       throw NoDataError() 
    }

    return try JSONDecoder().decode(User.self, from: d)
    })
)

另请参阅Preserving the Results of a Throwing Expression

关于ios - 作为构造函数关闭?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56608458/

相关文章:

ios - UIImagePicker 图像大小大于原始大小

ios - 应用程序在 IOS 6 上崩溃 - UIViewControllerHierarchyInconsistency

ios - 通过 iOS 登录 Facebook

swift - swift 和 swiftc 有什么区别?

ios - CollectionView ItemHeight 比 Collectionview 高度大

ios - Swift 希望 #selector 的参数暴露给 Objective-C

ios - UINavigationController子类方便初始化使子类常量init两次

javascript - FlatList contentContainerStyle -> justifyContent : 'center' causes issues with scrolling

iphone - 在 iOS 上使用与核心数据的关系

ios - SQLite.swift:在事件搜索中点击 UITableViewCell 时,由于强制展开 nil 值,应用程序崩溃