Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unwrapping Swift optional without variable reassignment

Tags:

swift

optional

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?

like image 875
Craig Otis Avatar asked Feb 25 '15 00:02

Craig Otis


People also ask

How do I unwrap optional in Swift?

An if statement is the most common way to unwrap optionals through optional binding. We can do this by using the let keyword immediately after the if keyword, and following that with the name of the constant to which we want to assign the wrapped value extracted from the optional. Here is a simple example.

How many ways we can unwrap an optional?

You can unwrap optionals in 4 different ways: With force unwrapping, using ! With optional binding, using if let. With implicitly unwrapped optionals, using !

Which operator is used to force unwrap an optional?

When you're certain that an instance of Optional contains a value, you can unconditionally unwrap the value by using the forced unwrap operator (postfix ! ). For example, the result of the failable Int initializer is unconditionally unwrapped in the example below.


1 Answers

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)
}
like image 180
Leo Dabus Avatar answered Sep 18 '22 10:09

Leo Dabus