Search code examples
swiftoption-type

Unwrapping Swift optional without variable reassignment


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 let childTitle = theItem.getChildItem()?.getTitle() {
    ...
}

But, when provided the variable as a parameter, I find myself either using:

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

or even just redefining it with the same name:

if let childTitle = childTitle { ... }

And I've started wondering if there is a shortcut or more efficient of performing a nil check for the sole purpose of using an existing variable. I've imagined something like:

if let childTitle { ... }

Does something like this exist, or at least an alternative to my above two interim solutions?


Solution

  • Edit/update: Xcode 14 • Swift 5.7

    swift-evolution proposal SE-0345 if let shorthand for shadowing an existing optional variable:

    if let childTitle {
    
    }
    

    guard let childTitle else {
        return
    }
    

    Original answer

    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)
    }