Azul
Azul

Reputation: 89

Is Array's count property an optional?

I created a type alias:

typealias areasOfStudyType = Array<Dictionary<String, String>>

Then a created an optional variable:

var areasOfStudy : areasOfStudyType? = nil

I need to use the number of elements of the array to put them in a table view so I typed:

areasOfAStudy?.count

I understand that if areasOfStudy is nil this line of code won't try to get the value of count because I'm using optional chaining. But when it's not nil it will return an Int.

However, the compiler complains that I haven't unwrap an optional and suggests that I type:

(areasOfAStudy?.count)!

Why is areasOfAStudy?.count an optional? When I look at the Array's reference documentation I read:

count
The number of elements the Array stores.

Declaration
var count: Int { get }

Upvotes: 1

Views: 455

Answers (2)

Lance
Lance

Reputation: 9012

This is just how optional chaining works.

If you have let value = nonOptional.property, assuming property and nonOptional is not optional, then value will not be an optional.

However, if you do let value = optionalObject?.property even though property is not defined as an optional, you accessed it through optional chaining (that's what the ?. means) so because optionalObject is optional, then value is optional as well because optionalObject could be nil.

Upvotes: 1

Josh Homann
Josh Homann

Reputation: 16327

The count is not optional but the array is. Therefore areasOfAStudy?.count is optional, because when areasOfAStudy is a nil count never gets called so it evalutes to nil.

var areasOfAStudy: [String]? = nil
//This evaluates to nil because areasOfAStudy is nil. The type of a is Int?
var a = areasOfAStudy?.count
print(type(of:a))

Upvotes: 1

Related Questions