swift - 在 Swift 中链接可选

标签 swift option-type

到目前为止,我一直在 Swift 2.1 中像这样解包 Optionals:

@IBOutlet var commentTextView: UITextView!

if let comment = user["comment"] as? String {
    commentTextView.text = comment
}

我从来没有真正考虑过它,但我认为我这样做的原因是因为我担心如果 user["comment"] 返回的不是字符串:

commentTextView.text = user["comment"] as? String

如果 user["comment"] 不是 String,赋值运算符左边的变量会被赋值并抛出错误还是赋值被跳过?

最佳答案

我想 user 实际上是一个字典 [String: Any] 和你真正做的事 if let comment =用户[“评论”]作为? String { ... } 不只是展开可选的,而是一个 conditional type casting (然后展开它的可选结果):

Use the conditional form of the type cast operator (as?) when you are not sure if the downcast will succeed. This form of the operator will always return an optional value, and the value will be nil if the downcast was not possible. This enables you to check for a successful downcast.

现在,回答你的问题,如果 user["comment"] 不是 String 那么结果将是 commentTextView.text 将被分配 nil 值,这很糟糕,因为它的类型是 String! ( implicitly unwrapped optional ) 我们 promise 它永远不会nil。所以,是的,会有一个错误,实际上是一个异常,但不是在你想要的地方,但此刻你的应用程序将尝试访问它的值,假设它不会是 nil.

您真正应该做什么取决于具体情况。

例如如果你可以让 user 成为像 [String: String] 这样的字典,那么你就可以真正地解开可选值并使用类似 if 的东西让 comment = user["comment"] { ... } 。或者,如果您完全确定 "comment" 键的值将始终存在,那么您可以只做 let comment = user["comment"]!.

但如果这不可能,那么您必须坚持使用向下转换,唯一可以做的就是使用它的强制形式,即 commentTextView.text = user["comment"] as!字符串。如果 "comment" 的值恰好不是 String 而是其他东西,这至少会在现场产生异常。

关于swift - 在 Swift 中链接可选,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33744942/

相关文章:

haskell - func::也许(Int) -> 也许(Int)

swift - 用 swift 在字典中迭代

swift - DispatchQueue.main.asyncAfter(截止日期: ) not working in command line app

ios - WKWebView - 如何获取我们刚刚触摸的输入类型的属性

java - 避免在控制逻辑中使用 isPresent() 和 get()

ios - 了解可选链接和可选解包选项

ios - Swift 在关闭时将值解包为 nil 但在代码的其他地方成功解包?

ios - 从服务器获取的质询与 ASAuthorization PlatformPublicKey CredentialProvider 凭证创建请求创建的质询不匹配

ios - 如何在 iOS 的 Collection View 中为内容偏移设置动画?

ios - Xcode git 显示多个存储库