Azul Azul - 1 month ago 9
Swift Question

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 }

Answer

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))