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?
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.
You can unwrap optionals in 4 different ways: With force unwrapping, using ! With optional binding, using if let. With implicitly unwrapped optionals, using !
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.
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With