【问题标题】:Swift: loop through a collection of type Any?Swift:循环遍历任何类型的集合?
【发布时间】:2021-01-22 22:56:09
【问题描述】:

我是学习 swift 的新手,遇到了这个问题,似乎找不到答案。我创建了一个 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)")
    }
}

提前感谢您的帮助!

【问题讨论】:

  • 只需将对象从Any 转换为[Any]
  • 第一条指令说“创建一个 [Any] 类型的集合”。那不是你做的。

标签: swift


【解决方案1】:

您应该创建[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
    }
}

这将打印出来

double 的值为 5.2
该字符串的值为 Hello
整数的值为 2
布尔值的值为 true
双精度值为 2.7
该字符串的值为 World
整数的值为 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
布尔值的值为 false

您可能也对这篇帖子感兴趣Flatten [Any] Array Swift

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-16
    • 2016-07-16
    • 2014-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多