Swift:遍历Any类型的集合?
我是快速学习的新手,遇到了这个问题,似乎找不到答案。我创建了一个 Any 类型的集合,其中包括 Double、String、Int 和 Bool。当我尝试遍历它时,出现错误:
“协议类型‘Any’的值不能符合‘Sequence’。
这是练习:
“创建一个 [Any] 类型的集合,包括集合中的一些双精度数、整数、字符串和布尔值。打印集合的内容。”
var items: Any = [5.2, "Hello", 2, true]
print(items)
“循环遍历集合。对于每个整数,打印“整数的值为“,然后是整数值。对双精度数、字符串和布尔值重复这些步骤。”
for item in items {
if let unwrappedItem = item as? Int {
print("The integer has a value of (item)")
} else if let unwrappedItem = item as? Double {
print("The integer has a value of (item)")
}
}
在此先感谢您的帮助!
回答
您应该创建一个 type[Any]而不是Any. 然后您可以切换每个项目并将其转换为各自的类型:
let items: [Any] = [5.2, "Hello", 2, true, 2.7, "World", 10, false]
for item in items {
switch item {
case let item as Int: print("The integer has a value of (item)")
case let item as Double: print("The double has a value of (item)")
case let item as String: print("The string has a value of (item)")
case let item as Bool: print("The boolean has a value of (item)")
default: break
}
}
这将打印
双有5.2的值
,该字符串具有你好值
的整数具有2的值
布尔的数值为真
双具有2.7的值
,该字符串具有世界的价值
整数具有10的值
的布尔值的值为 false
如果您需要分别迭代每个类型,您可以使用 case let 并将每个元素转换为所需的类型:
for case let item as Int in items {
print("The integer has a value of (item)")
}
for case let item as Double in items {
print("The double has a value of (item)")
}
for case let item as String in items {
print("The string has a value of (item)")
}
for case let item as Bool in items {
print("The boolean has a value of (item)")
}
这将打印
整数的值为 2
整数的值为 10
双精度的值为 5.2
双精度的值为 2.7
字符串的值为 Hello
字符串的值为 World
布尔值的值为 true
The布尔值的值为 false
您可能还对这篇文章Flatten [Any] Array Swift感兴趣