【发布时间】:2014-10-02 16:44:19
【问题描述】:
我掌握(我认为)optional types in Swift 的基础知识,并且粗略了解? 和! 之间的区别,但我仍然对使用这些功能时得到的一些结果感到困惑——尤其是Some <T> 的角色,以及它与 <T> 本身的不同之处;我在某些情况下收到的一些特定错误消息;以及在我期望<T> 的情况下,Some <T> 似乎会弹出。
但我也觉得,即使我理解了个别案例,我对图片的把握也越来越远了,我觉得这里有一个密码,只要我完全理解,我就可以破译一个 简单的例子——罗塞塔石碑,如果你愿意的话——用于!、?、可选值和解包。
例如,这里是一个简单且(我认为)详尽的基本案例目录:
class Foo {
var one:String = "";
var two:String?
var three:String!
}
let test = Foo() // {one "" nil nil}
test.one
//test.one? // ERROR: ? requires optional type
//test.one! // ERROR: ! requires optional type
// ?, unassigned
test.two // nil
test.two? // nil
//test.two! // ERROR: EXEC_BAD_INSTRUCTION
test.two == nil // true
test.two? == nil // true
//test.two! == nil // ERROR: Cannot invoke == with an argument list of type (@lvalue String, NilLiteralConvertable)
//test.two.isEmpty // ERROR: String? does not have .isEmpty
test.two?.isEmpty // nil
//test.two!.isEmpty // ERROR: EXEC_BAD_INSTRUCTION
// !, unassigned
test.three // nil
test.three? // nil
//test.three! // ERROR: EXEC_BAD_INSTRUCTION
test.three == nil // true
test.three? == nil // true
//test.three! == nil // ERROR: Cannot invoke == with an argument list of type (@lvalue String, NilLiteralConvertable)
//test.three.isEmpty // ERROR: EXEC_BAD_INSTRUCTION
test.three?.isEmpty // nil
//test.three!.isEmpty // ERROR: EXEC_BAD_INSTRUCTION
test.two = "???" // {one "" {Some "???"} nil}
test.three = "!!!" // {one "" {Some "???"} three "!!!"}
// ?, assigned
test.two // {Some "???"}
test.two? // {Some "???"}
test.two! // "???"
test.two == nil // false
test.two? == nil // false
//test.two! == nil // ERROR: Cannot invoke == with an argument list of type (@lvalue String, NilLiteralConvertable)
//test.two.isEmpty // ERROR: String? does not have .isEmpty
test.two?.isEmpty // {Some false}
test.two!.isEmpty // false
// !, assigned
test.three // "!!!"
test.three? // {Some "!!!"}
test.three! // "!!!"
test.three == nil // false
test.three? == nil // false
//test.three! == nil // ERROR: Cannot invoke == with an argument list of type (@lvalue String, NilLiteralConvertable)
test.three.isEmpty // false
test.three?.isEmpty // {Some false}
test.three!.isEmpty // false
如果有人可以对此进行注释,解释每个案例的情况,我认为该答案可以作为 Swift 的这些功能如何工作的可靠参考。
【问题讨论】:
-
注意:我知道有很多关于这个的问题(以及很多很好的答案);我都读过了。我在这里寻找的有点不同:在一个简单示例的上下文中,解释规则如何在每个特定情况下发挥作用。此外,这不是关于使用的问题。我想我明白了这些功能的原因。
标签: syntax swift semantics optional