What does an exclamation mark mean in the Swift language?

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

    john is an optional var and it can contain a nil value. To ensure that the value isn't nil use a ! at the end of the var name.

    From documentation

    “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.”

    Another way to check non nil value is (optional unwrapping)

        if let j = json {
            // do something with j
        }
    

提交回复
热议问题