Woody
Woody

Reputation: 1787

'[String]?' does not have a member named 'count' in Swift

I have the following swift code:

var Data = ["first" : ["Rob ", "Gladys", "Hugh"],
"last" : ["Banks", "Friday", "Mungus"]
]

var elementCount = 0
var key = "first"
var elements = data[key!]
elementCount = elements.count

but I get the following error on the last line of this code:

'[String]?' does not have a member named 'count'

How do I fix this error and why is it happening?

** EDIT **

What if I also wanted to extract the item within elements at a particular index. So, for example:

var myIndex = 1

var firstname = elements[myIndex]

this gives the error

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

Upvotes: 0

Views: 601

Answers (1)

Leo Dabus
Leo Dabus

Reputation: 236360

This error means your dictionary returns an optional array and you need to unwrap it before trying to access its property count. You have to do like this:

let data = ["first" : ["Rob ", "Gladys", "Hugh"],"last" : ["Banks", "Friday", "Mungus"]]

var elementCount = 0
let key = "first"
if let elements = data[key] {
    elementCount = elements.count
}

Upvotes: 2

Related Questions