What does an exclamation mark mean in the Swift language?

后端 未结 22 2676
南方客
南方客 2020-11-22 03:47

The Swift Programming Language guide has the following example:

class Person {
    let name: String
    init(name: String) { self.name = name }
    var apar         


        
22条回答
  •  南旧
    南旧 (楼主)
    2020-11-22 04:19

    If john were an optional var (declared thusly)

    var john: Person?
    

    then it would be possible for john to have no value (in ObjC parlance, nil value)

    The exclamation point basically tells the compiler "I know this has a value, you don't need to test for it". If you didn't want to use it, you could conditionally test for it:

    if let otherPerson = john {
        otherPerson.apartment = number73
    }
    

    The interior of this will only evaluate if john has a value.

提交回复
热议问题