gpt4 book ai didi

ios - 使用 swift 遍历 NSDictionary

转载 作者:可可西里 更新时间:2023-10-31 23:55:21 26 4
gpt4 key购买 nike

我不明白为什么这段Objective-C代码:

id object = nil;
NSEnumerator *enumerator = ...;
while ((object = [enumerator nextObject])) {...}

不能像这样在 Swift 中翻译:

var key:AnyObject!
let enumerator:NSEnumerator = myNSDictionary.keyEnumerator()
while ( (object = enumerator.nextObject()) ) {...}

我有这个错误:

Type '()' does not conform to protocol 'BooleanType'

最佳答案

您应该按如下方式枚举字典(在 here 中有更详细的描述):

测试字典声明:

var airports = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]

枚举键和值:

for (airportCode, airportName) in airports {
print("\(airportCode): \(airportName)")
}
// YYZ: Toronto Pearson
// LHR: London Heathrow

仅枚举键:

for airportCode in airports.keys {
print("Airport code: \(airportCode)")
}
// Airport code: YYZ
// Airport code: LHR

仅枚举值:

for airportName in airports.values {
print("Airport name: \(airportName)")
}
// Airport name: Toronto Pearson
// Airport name: London Heathrow

也许您选择使用 NSEnumerator 有更深层次的原因,但如果不是,从 Swift 的角度来看,上面的方法要优雅得多。

关于ios - 使用 swift 遍历 NSDictionary,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32997258/

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