如何理解 swift 中的 `!` 和 `?`?

How to understand `!` and `?` in swift?

我是 swift.When 的新手,我声明了一个变量,或者当我得到一个实例的 属性 时,我发现“!”和 ”?” is everywhere.Doing Objective-C 这样的事情很容易,你甚至可以不知道 class 和 "id" 的类型 type.Why 我们需要 !? ?

我想知道设计!?的原因,而不是如何利用them.What具有可选类型的优势?

嗯...

? (Optional) indicates your variable may contain a nil value while ! (unwrapper) indicates your variable must have a memory (or value) when it is used (tried to get a value from it) at runtime.

主要区别在于,当可选值为 nil 时,可选链接会优雅地失败,而当可选值为 nil 时,强制展开会触发运行时错误。

为了反映可以在 nil 值上调用可选链接这一事实,可选链接调用的结果始终是一个可选值,即使您正在查询的 属性、方法或下标 returns 是一个非可选值。您可以使用此可选 return 值来检查可选链接调用是否成功(returned 可选包含一个值),或者由于链中的 nil 值而未成功(returned 可选值为 nil)。

具体来说,可选链调用的结果与预期的 return 值具有相同的类型,但包装在可选的。通常 return 是 Int 的 属性 将 return 是 Int? 当通过可选链接访问时。

var defaultNil : Int?  // declared variable with default nil value
println(defaultNil) >> nil  

var canBeNil : Int? = 4
println(canBeNil) >> optional(4)

canBeNil = nil
println(canBeNil) >> nil

println(canBeNil!) >> // Here nil optional variable is being unwrapped using ! mark (symbol), that will show runtime error. Because a nil optional is being tried to get value using unwrapper

var canNotBeNil : Int! = 4
print(canNotBeNil) >> 4

var cantBeNil : Int = 4
cantBeNil = nil // can't do this as it's not optional and show a compile time error

Here is basic tutorial in detail, by Apple Developer Committee.

来自 Apple 文档:

You use optionals in situations where a value may be absent. An optional represents two possibilities: Either there is a value, and you can unwrap the optional to access that value, or there isn’t a value at all.

The concept of optionals doesn’t exist in C or Objective-C. The nearest thing in Objective-C is the ability to return nil from a method that would otherwise return an object, with nil meaning “the absence of a valid object.”

If you define an optional variable without providing a default value, the variable is automatically set to nil for you:

var surveyAnswer: String?

You can use an if statement to find out whether an optional contains a value by comparing the optional against nil. You perform this comparison with the “equal to” operator (==) or the “not equal to” operator (!=).

If an optional has a value, it is considered to be “not equal to” nil:

if convertedNumber != nil {
print("convertedNumber contains some integer value.") 
}

Once you’re sure that the optional does contain a value, you can access its underlying value by adding an exclamation mark (!) to the end of the optional’s name. The exclamation mark effectively says, “I know that this optional definitely has a value; please use it.” This is known as forced unwrapping of the optional’s value:

print("convertedNumber has an integer value of \(convertedNumber!).")