A O A O - 3 years ago 53
Swift Question

Why does the compiler tell me I need to unwrap a Bool (non-optional?)

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?

Answer Source

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
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download