What does an exclamation mark mean in the Swift language?

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

    ASK YOURSELF

    • Does the type person? have an apartment member/property? OR
    • Does the type person have an apartment member/property?

    If you can't answer this question, then continue reading:

    To understand you may need super-basic level of understanding of Generics. See here. A lot of things in Swift are written using Generics. Optionals included

    The code below has been made available from this Stanford video. Highly recommend you to watch the first 5 minutes

    An Optional is an enum with only 2 cases

    enum Optional{
        case None
        case Some(T)
    }
    
    let x: String? = nil //actually means:
    
    let x = Optional.None
    

    let x :String? = "hello" //actually means:
    
    let x = Optional.Some("hello")
    

    var y = x! // actually means:
    
    switch x {
    case .Some(let value): y = value
    case .None: // Raise an exception
    }
    

    Optional binding:

    let x:String? = something
    if let y = x {
        // do something with y
    }
    //Actually means:
    
    switch x{
    case .Some(let y): print)(y) // or whatever else you like using 
    case .None: break
    }
    

    when you say var john: Person? You actually mean such:

    enum Optional{
    case .None
    case .Some(Person)
    }
    

    Does the above enum have any property named apartment? Do you see it anywhere? It's not there at all! However if you unwrap it ie do person! then you can ... what it does under the hood is : Optional.Some(Person(name: "John Appleseed"))


    Had you defined var john: Person instead of: var john: Person? then you would have no longer needed to have the ! used, because Person itself does have a member of apartment


    As a future discussion on why using ! to unwrap is sometimes not recommended see this Q&A

提交回复
热议问题