Swift:循环遍历 Any 类型的集合?

标签 swift

我是学习 swift 的新手,我遇到了这个问题,但似乎找不到答案。我创建了一个 Any 类型的集合,其中包括 Double、String、Int 和 Bool。当我尝试循环它时,出现错误:

"Value of protocol type 'Any' cannot conform to 'Sequence'.

这是练习:

"Create a collection of type [Any], including a few doubles, integers, strings, and booleans within the collection. Print the contents of the collection."

var items: Any = [5.2, "Hello", 2, true]
print(items)

"Loop through the collection. For each integer, print "The integer has a value of ", followed by the integer value. Repeat the steps for doubles, strings and booleans."

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。然后您可以切换每个项目并将其转换为各自的类型:

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
    }
}

这将打印

The double has a value of 5.2
The string has a value of Hello
The integer has a value of 2
The boolean has a value of true
The double has a value of 2.7
The string has a value of World
The integer has a value of 10
The boolean has a value of 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)")
}

这将打印

The integer has a value of 2
The integer has a value of 10
The double has a value of 5.2
The double has a value of 2.7
The string has a value of Hello
The string has a value of World
The boolean has a value of true
The boolean has a value of false

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

关于Swift:循环遍历 Any 类型的集合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65853864/

相关文章:

ios - 识别语音到文本 Swift

ios - 将文本放在 UIlabel 的顶部

ios - 使用 swift 3 更改 iOS 中的按钮标题不起作用

ios - NSDecimalNumber 是否有等效的 RoundHalfUp ?

ios - Swift:从 SwiftyJson 结果创建结果表

swift : pressed label to copy text to the clipboard

ios - 我的 CoreGraphics 代码运行非常缓慢。我怎样才能让这个自定义的 UIScrollView 表现得更好?

arrays - 在 Swift 中将对象类型更改为子类的实例

ios - 每周重复通知和具体开始日期

ios - XCode 6.1 iOS提交