According the the Swift header for String
the property isEmpty
is a Bool
(not an optional right?)
public var isEmpty: Bool { get }
but in my code, when I try to write:
!sender.titleOfSelectedItem?.isEmpty
Value of optional type
Bool?
not unwrapped, did you mean to use "?" or "!"
Why does the compiler think that isEmpty
is an optional?
Is it because the object that contains the property is currently an optional?
titleOfSelectedItem
is a String?
or am I just missing something entirely, here?
Unwrap an optional type with the nil coalescing operator If a nil value is found when an optional value is unwrapped, an additional default value is supplied which will be used instead. You can also write default values in terms of objects.
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.
A common way of unwrapping optionals is with if let syntax, which unwraps with a condition. If there was a value inside the optional then you can use it, but if there wasn't the condition fails. For example: if let unwrapped = name { print("\(unwrapped.
Unwrapping an optional means that you are now casting that type as non-optional. This will generate a new type and assign the value that resided within that optional to the new non-optional type. This way you can perform operations on that variable as it has been guaranteed by the compiler to have a solid value.
sender.titleOfSelectedItem?.isEmpty
is an optional chain and has the type Bool?
because it can return nil
if titleOfSelectedItem
is nil
.
You should decide how you want to handle the nil
case. You can combine the optional chain with the nil coalescing operator ??
to safely unwrap the result:
// treat nil as empty
let empty = sender.titleOfSelectedItem?.isEmpty ?? true
or you can compare the value to false
:
if sender.titleOfSelectedItem?.isEmpty == false {
// value isn't nil and it isn't empty
}
or you can compare to value to true
:
if sender.titleOfSelectedItem?.isEmpty == true {
// value isn't nil and it is an empty String
}
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