gpt4 book ai didi

arrays - swift 3 : binary operator cannot be applied to operands of type int and 'Int?'

转载 作者:搜寻专家 更新时间:2023-11-01 06:16:23 24 4
gpt4 key购买 nike

我在尝试像这样进行 for 循环时遇到错误

for i in  0..<firstJSON["boxGroups"].array?.count{
existingGroups.append(firstJSON["boxGroups"][0]["name"].stringValue)
}

Xcode 提示“二元运算符不能应用于 int 和‘Int?’类型的操作数”

最佳答案

您遇到的问题是因为 Optional Chaining , array 属性返回可选类型,这样你的 count 属性也返回可选对象。因此,最好用 if letguard let 包裹可选。

此外,在 for 循环 中,不是使用 i 访问数组的每个对象,而是使用 0 访问第一个对象。

if let boxGroupsArray = firstJSON["boxGroups"].array {
for i in 0..<boxGroupsArray.count{
existingGroups.append(boxGroupsArray[i]["name"].stringValue)
}
}

使用 flatMap 代替 for loop 是更好的选择

if let boxGroupsArray = firstJSON["boxGroups"].array {
existingGroups = boxGroupsArray.flatMap { $0["name"].string }
}

关于arrays - swift 3 : binary operator cannot be applied to operands of type int and 'Int?' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44063230/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com