bpa
bpa

Reputation: 183

Access to Any Object in Swift

i create an array of subviews

var subviews  = self.navigationController?.navigationBar.subviews

type of "subviews" variable is "AnyObject". I try get subview:

var subview=subviews[0]

but i receive an error:

'[AnyObject]?' does not have a member named 'subscript'

How to access the elements of an array?

Upvotes: 1

Views: 1024

Answers (1)

Antonio
Antonio

Reputation: 72810

This expression:

self.navigationController?.navigationBar.subviews

returns an optional, so you have to unwrap the array from the optional before using it:

var subviews  = self.navigationController?.navigationBar.subviews
if let subviews = subviews {
    // Better check for array length before accessing to the 1st element
    var subview = subviews [0]
}

Suggested reading: Optionals

Upvotes: 1

Related Questions