Unwrapping Swift optional without variable reassignment

后端 未结 2 484
北荒
北荒 2020-12-15 13:55

When using optional binding to unwrap a single method call (or optional chaining for a long method call chain), the syntax is clear and understandable:

if le         


        
2条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-15 14:34

    No. You should unwrap your optionals just redefining it with the same name as you mentioned. This way you don't need to create a second var.

    func someFunction(childTitle: String?) {
        if let childTitle = childTitle {
            ...
        }
    }
    

    update: Xcode 7.1.1 • Swift 2.1

    You can also use guard as follow:

    func someFunction(childTitle: String?) {
        guard let childTitle = childTitle else {
            return
        }
    
        // childTitle it is not nil after the guard statement
        print(childTitle)
    }
    

提交回复
热议问题