Swift 如何循环到数组中并切换到其索引
我有以下数组:Swift 如何循环到数组中并切换到其索引,swift,switch-statement,Swift,Switch Statement,我有以下数组: let dict = [("Steve", 17), ("Marc", 38), ("Xavier", 21), ("Rolf", 45), ("Peter", 67), ("Nassim", 87), ("Raj", 266), ("Paul", 220), ("Bill"
let dict = [("Steve", 17),
("Marc", 38),
("Xavier", 21),
("Rolf", 45),
("Peter", 67),
("Nassim", 87),
("Raj", 266),
("Paul", 220),
("Bill", 392)]
如何循环并切换到索引,以便在前三个、后三个和后三个中进行操作。您可以通过where子句指定索引的步骤:
for index in 0..<dict.count where index % 3 == 0 {
// here you can do action with index, index + 1, index + 2 items in way you need
}
您可以使用dict.enumerated获取idx项元组序列,然后for可以通过该序列进行枚举。例如:
let dict = [("Steve", 17),
("Marc", 38),
("Xavier", 21),
("Rolf", 45),
("Peter", 67),
("Nassim", 87),
("Raj", 266),
("Paul", 220),
("Bill", 392)]
for (idx, item) in dict.enumerated() {
let (name, value) = item
switch (idx / 3) {
case 0:
print("\(name) is in the first group")
case 1:
print("\(name) is in the second group")
case 2:
print("\(name) is in the third group")
default:
print("\(name) not in first 3 groups")
}
print("value is \(value)")
}
输出:
Players: Steve, Marc, Xavier
Result: 199
Result: 878
或者等效地,您可以直接打开它,而不是基于索引进行整数计算,但使用一个范围来处理以下情况:
switch idx {
case 0...2:
print("\(name) is in the first group")
case 3...5:
print("\(name) is in the second group")
case 6...8:
print("\(name) is in the third group")
default:
print("\(name) not in first 3 groups")
}
您可以使用数组扩展按给定大小的块拆分数组:
extension Array {
func chunked(by distance: IndexDistance) -> [[Element]] {
return stride(from: startIndex, to: endIndex, by: distance).map {
let newIndex = index($0, offsetBy: distance, limitedBy: endIndex) ?? endIndex
return Array(self[$0 ..< newIndex])
}
}
}
输出:
Players: Steve, Marc, Xavier
Result: 199
Result: 878
请不要在标题中添加标签,尤其不要无故在标题中使用特殊字符。这使得将来有类似问题的人更难找到你的问题。将元组数组命名为dict是非常误导的。
Players: Steve, Marc, Xavier
Result: 199
Result: 878