作者热门文章
- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
我不明白为什么这段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/
我是一名优秀的程序员,十分优秀!