Reputation: 9509
I am struggling to understand why the Array of optionals .first
returns double wrapped optional in this case and how to avoid it:
class MyBanana {
}
let bananas = [MyBanana?]()
let first: MyBanana? = bananas.first
On the last line i get the following error:
Cannot convert value of type 'MyBanana??' to specified type 'MyBanana?'
Upvotes: 0
Views: 471
Reputation: 54151
I solved it like this:
let first: MyBanana? = bananas.isEmpty ? nil : bananas[0]
Although, in my opinion, first
should handle such a situation without complaining.
Upvotes: 1
Reputation: 4173
You have an array of Optional MyBanana
s, and .first
gives you back the first element of the array as an optional.
Calling .first
on an array is equivalent to this code snippet:
if array.count == 0 {
return nil
} else {
return array[0]
}
It's a safe way of getting the first element of an array.
When you call .first
on an array of type Array<T>
, you get back an element of type T?
. bananas
is of type Array<MyBanana?>
. Therefore, T = MyBanana?
and .first
gives back an element of type T? = MyBanana??
.
I would strongly recommend you do not keep an array of optional elements, since .first
already gives you back an optional.
Upvotes: 2