Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

swift

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?

like image 702
A O Avatar asked Jul 25 '17 23:07

A O


People also ask

What will happen if you try to unwrap an optional that contains nil like so?

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.

How do you unwrap optional type?

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 can we unwrap an optional value?

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.

What does unwrapping mean in reference to values in Swift?

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.


1 Answers

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
}
like image 171
vacawama Avatar answered Sep 29 '22 08:09

vacawama