2

I'm new to learning swift and I ran into this issue and can't seem to find an answer for it. I create a collection of type Any that includes a Double, String, Int and Bool. When I attempt to loop through it I get an error:

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

Here is the exercise:

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

Thanks in advance for the help!

pawello2222
  • 46,897
  • 22
  • 145
  • 209
TBranham
  • 33
  • 4

1 Answers1

5

You were supposed to create an object of type [Any] instead of Any. Then you can switch each item and cast it to its respective type:

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

This will print

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


If you need to iterate each type separately you can use for case let and cast each element to the desired type:

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

This will print

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

You may also be interest in this post Flatten [Any] Array Swift

vacawama
  • 150,663
  • 30
  • 266
  • 294
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571