Roman
Roman

Reputation: 1500

Why are elements of Array in this case optional?

let x = Array(repeating: "test", count: 3)
x.first.count

I've got an error:
"Value of optional type 'String?' must be unwrapped to refer to member 'count' of wrapped base type 'String'"

Why should I write: x.first?.count ?
I'm pretty sure that the first element of this array is not nil

Upvotes: 0

Views: 379

Answers (2)

Mojtaba Hosseini
Mojtaba Hosseini

Reputation: 119686

As you said, You are the one who is sure the first element is not nil. So You are the one who should force the compiler to unwrapped it!

The only thing compiler knows is that maybe the array will be empty like: [], and there where no elements in it, So it returns optional even if you sure.

So if you are really sure, just force unwrap it:

x.first!.count

Upvotes: 1

Shehata Gamal
Shehata Gamal

Reputation: 100533

I'm pretty sure that the first element of this array is not nil

Yes but it's implementation doesn't know that , it's written also in case no values exist so optional comes to rescue

extension Array { 
   @inlinable public var first: Element? { get }
}

Upvotes: 2

Related Questions