'[串]?'在Swift中没有名为'count'的成员

时间:2015-04-12 04:04:04

标签: swift

我有以下快速代码:

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

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

但是我在这段代码的最后一行收到以下错误:

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

如何修复此错误以及为什么会发生错误?

** 编辑 **

如果我还想在特定索引的elements内提取项目,该怎么办?所以,例如:

var myIndex = 1

var firstname = elements[myIndex]

这给出了错误

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

1 个答案:

答案 0 :(得分:2)

此错误表示您的字典返回一个可选数组,您需要在尝试访问其属性计数之前将其解包。你必须这样做:

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

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