7

Is there are better way to do this? Something that looks nicer syntax wise?

let a : [Any] = [5,"a",6]
for item in a { 
  if let assumedItem = item as? Int {
     print(assumedItem) 
  } 
}

Something like this, but then with the correct syntax?

  for let item in a as? Int { print(item) }
user965972
  • 2,489
  • 2
  • 23
  • 39

4 Answers4

7

With Swift 5, you can choose one of the following Playground sample codes in order to solve your problem.


#1. Using as type-casting pattern

let array: [Any] = [5, "a", 6]

for case let item as Int in array {
    print(item) // item is of type Int here
}

/*
 prints:
 5
 6
 */

#2. Using compactMap(_:) method

let array: [Any] = [5, "a", 6]

for item in array.compactMap({ $0 as? Int }) {
    print(item) // item is of type Int here
}

/*
 prints:
 5
 6
 */

#3. Using a where clause and is type-casting pattern

let array: [Any] = [5, "a", 6]

for item in array where item is Int {
    print(item) // item conforms to Any protocol here
}

/*
 prints:
 5
 6
 */

#4. Using filter(_:​) method

let array: [Any] = [5, "a", 6]

for item in array.filter({ $0 is Int }) {
    print(item) // item conforms to Any protocol here
}

/*
 prints:
 5
 6
 */
Imanou Petit
  • 89,880
  • 29
  • 256
  • 218
6

If you're using Swift 2:

let array: [Any] = [5,"a",6]

for case let item as Int in array {
    print(item)
}
ABakerSmith
  • 22,759
  • 9
  • 68
  • 78
2

Two solutions

let a = [5,"a",6]

a.filter {$0 is Int}.map {print($0)}

or

for item in a where item is Int {
    print(item)
}

actually there are no optionals at all in the array

vadian
  • 274,689
  • 30
  • 353
  • 361
0

You could also use flatMap to convert the array into [Int].

let a : [Any] = [5,"a",6]
for item in a.flatMap({ $0 as? Int }) {
    print(item)
}
hennes
  • 9,147
  • 4
  • 43
  • 63