Unwrapping Swift optional without variable reassignment

后端 未结 2 478
北荒
北荒 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)
    }
    
    0 讨论(0)
  • 2020-12-15 14:35

    Here's the only alternative I'm aware of.

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

    But then childTitle is still an optional, so you would have to unwrap it every time you use it: childTitle!.doSomething(). It shouldn't affect performance, though.

    0 讨论(0)
提交回复
热议问题