What does an exclamation mark mean in the Swift language?

后端 未结 22 2653
南方客
南方客 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:18

    TL;DR

    What does an exclamation mark mean in the Swift language?

    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:

    Example

    let possibleString: String? = "An optional string."
    print(possibleString!) // requires an exclamation mark to access its value
    // prints "An optional string."
    
    let assumedString: String! = "An implicitly unwrapped optional string."
    print(assumedString)  // no exclamation mark is needed to access its value
    // prints "An implicitly unwrapped optional string."
    

    Source: https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html#//apple_ref/doc/uid/TP40014097-CH5-XID_399

提交回复
热议问题