What does an exclamation mark mean in the Swift language?

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

    To put it simply, exclamation marks mean an optional is being unwrapped. An optional is a variable that can have a value or not -- so you can check if the variable is empty, using an if let statement as shown here, and then force unwrap it. If you force unwrap an optional that is empty though, your program will crash, so be careful! Optionals are declared by putting a question mark at the end of an explicit assignment to a variable, for example I could write:

    var optionalExample: String?
    

    This variable has no value. If I were to unwrap it, the program would crash and Xcode would tell you you tried to unwrap an optional with a value of nil.

    Hope that helped.

提交回复
热议问题