【问题标题】:How to get array key values from loop in Swift 3如何从 Swift 3 中的循环中获取数组键值
【发布时间】:2018-01-19 04:01:01
【问题描述】:

我正在将我的代码从 Swift 2.3 更新到 Swift 3,我在 Swift 中从循环中获取数组键值时遇到了这些困难:

var countryarray = NSMutableArray()

self.GetCountriesResult = (responseJSON.objectForKey("GetCountriesResult") as? NSArray)!

for i in 0 ..< self.GetCountriesResult.count {
    self.countryarr = self.GetCountriesResult.objectAtIndex(i).objectForKey("countryname") as? String ?? ""
    self.countryarray.addObject(self.countryarr)
}

【问题讨论】:

  • 您使用的是 Swift 3?摆脱 NSArray 的东西(几乎所有以“NS”开头的东西)并改用 Swift 类型。你得到了什么错误?我猜,Any 没有objectForKey() 或类似的东西。这是一个常见的问题。你需要告诉编译器self.GetCountriesResult.objectAtIndex(i) 是一个Dictionary 并且你可以在上面调用objectForKey
  • 错误提示?
  • 如果可以,请提供 JSON 响应示例。

标签: ios arrays for-loop swift3 swift2.3


【解决方案1】:

map 在这种情况下比for-in 更适合:

guard let json = responseJSON["GetCountriesResult"] as? [String : AnyObject]
    else { return }

self.GetCountriesResult = json

let countryArray = self.GetCountriesResult.map {
    return $0["countryname"] as? String ?? ""
}

// OR

guard let json = responseJSON["GetCountriesResult"] as? [String : AnyObject]
    else { return }

let countries = json.map {
    return $0["countryname"] as? String ?? ""
}



建议:阅读以下 Swift 风格指南:

【讨论】:

    猜你喜欢
    • 2021-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-20
    • 1970-01-01
    相关资源
    最近更新 更多