gpt4 book ai didi

swift - Swift 中的“[String] ?' does not have a member named ' 计数”

转载 作者:行者123 更新时间:2023-11-28 13:14:29 26 4
gpt4 key购买 nike

我有以下快速代码:

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'

最佳答案

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

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

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

关于swift - Swift 中的“[String] ?' does not have a member named ' 计数”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29585825/

26 4 0