如何在 Swift 5 中循环字典?
How to loop over a dictionary in Swift 5?
在 Swift 4 中,我可以使用下面的代码,但在 Swift 5 中,我收到以下错误:Type 'Dictionary<String, String>.Values.Iterator' does not conform to protocol 'Sequence'
guard let userIds = users.values.makeIterator() else { return }
for userId in userIds {
// User setup
}
现在 Swift 5 中正确的方法是什么?
你可以简单地做
for (_, userId) in users {
// User setup
}
let dictionary: [String: Int] = ["a": 1, "b": 2]
for (key, value) in dictionary {
print(key, value)
}
您可以像这样尝试迭代器:
let users = ["a":11, "b":12]
var userIds = users.values.makeIterator()
while let next = userIds.next() {
print(next) // 11 \n 12
}
Swift4、swift5及以上
let dict: [String: Any] = ["a": 1, "b": "hello", "c": 3]
for (key, value) in dict {
print(key, value)
}
另外:
let x = [
"kitty": 7,
"bob": 2,
"orange": 44
]
x.forEach { t in
print("key = \(t.key); value = \(t.value)")
}
这显然自 Swift 3 以来可用。Link to standard library docs on Dictionary
type。
在 Swift 4 中,我可以使用下面的代码,但在 Swift 5 中,我收到以下错误:Type 'Dictionary<String, String>.Values.Iterator' does not conform to protocol 'Sequence'
guard let userIds = users.values.makeIterator() else { return }
for userId in userIds {
// User setup
}
现在 Swift 5 中正确的方法是什么?
你可以简单地做
for (_, userId) in users {
// User setup
}
let dictionary: [String: Int] = ["a": 1, "b": 2]
for (key, value) in dictionary {
print(key, value)
}
您可以像这样尝试迭代器:
let users = ["a":11, "b":12]
var userIds = users.values.makeIterator()
while let next = userIds.next() {
print(next) // 11 \n 12
}
Swift4、swift5及以上
let dict: [String: Any] = ["a": 1, "b": "hello", "c": 3]
for (key, value) in dict {
print(key, value)
}
另外:
let x = [
"kitty": 7,
"bob": 2,
"orange": 44
]
x.forEach { t in
print("key = \(t.key); value = \(t.value)")
}
这显然自 Swift 3 以来可用。Link to standard library docs on Dictionary
type。