When should I compare an optional value to nil?

前端 未结 5 1536
时光取名叫无心
时光取名叫无心 2020-11-22 10:22

Quite often, you need to write code such as the following:

if someOptional != nil {
    // do something with the unwrapped someOptional e.g.       
    someF         


        
5条回答
  •  情深已故
    2020-11-22 11:18

    You there is one way. It is called Optional Chaining. From documentation:

    Optional chaining is a process for querying and calling properties, methods, and subscripts on an optional that might currently be nil. If the optional contains a value, the property, method, or subscript call succeeds; if the optional is nil, the property, method, or subscript call returns nil. Multiple queries can be chained together, and the entire chain fails gracefully if any link in the chain is nil.

    Here is some example

    class Person {
        var residence: Residence?
    }
    
    class Residence {
        var numberOfRooms = 1
    }
    
    let john = Person()
    
    if let roomCount = john.residence?.numberOfRooms {
        println("John's residence has \(roomCount) room(s).")
    } else {
        println("Unable to retrieve the number of rooms.")
    }
    // prints "Unable to retrieve the number of rooms."
    

    You can check the full article here.

提交回复
热议问题