What is the difference between String? and String!

2019-01-03 01:58发布

In The Swift Programming Language (book of Apple) I've read that you can create optional variables in 2 ways: using a question mark (?) or by using an exclamation mark (!).

The difference is that when you get the value of an optional with (?) you have to use an exclamation mark every time you want the value:

var str: String? = "Question mark?"
println(str!) // Exclamation mark needed
str = nil    

While with an (!) you can get it without a suffix:

var str: String! = "Exclamation mark!"
println(str) // No suffix needed
str = nil

What is the difference and why are there 2 ways if there is no difference at all?

标签: ios swift
7条回答
干净又极端
2楼-- · 2019-01-03 03:01

in the optional chaining section you find the answer:

example class:

class Person {
    var residence: Residence?
}

class Residence {
    var numberOfRooms = 1
}

If you try to access the numberOfRooms property of this person’s residence, by placing an exclamation mark after residence to force the unwrapping of its value, you trigger a runtime error, because there is no residence value to unwrap:

let roomCount = john.residence!.numberOfRooms
// this triggers a runtime error

The code above succeeds when john.residence has a non-nil value and will set roomCount to an Int value containing the appropriate number of rooms. However, this code always triggers a runtime error when residence is nil, as illustrated above.

Optional chaining provides an alternative way to access the value of numberOfRooms. To use optional chaining, use a question mark in place of the exclamation mark:

if let roomCount = john.residence?.numberOfRooms {
    println("John's residence has \(roomCount) room(s).")
} else {
    println("Unable to retrieve the number of rooms.")
}
// prints "Unable to retrieve the number of rooms."
查看更多
登录 后发表回答