What does an exclamation mark mean in the Swift language?

后端 未结 22 2660
南方客
南方客 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条回答
  •  猫巷女王i
    2020-11-22 04:22

    John is an optional Person, meaning it can hold a value or be nil.

    john.apartment = number73
    

    is used if john is not an optional. Since john is never nil we can be sure it won't call apartment on a nil value. While

    john!.apartment = number73
    

    promises the compiler that john is not nil then unwraps the optional to get john's value and accesses john's apartment property. Use this if you know that john is not nil. If you call this on a nil optional, you'll get a runtime error.

    The documentation includes a nice example for using this where convertedNumber is an optional.

    if convertedNumber {
        println("\(possibleNumber) has an integer value of \(convertedNumber!)")
    } else {
        println("\(possibleNumber) could not be converted to an integer")
    }
    

提交回复
热议问题