Quick quick listing options

Is there a better way to do this? Something that looks like a stronger syntax?

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) }
+5
source share
4 answers

If you are using Swift 2:

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

for case let item as Int in array {
    print(item)
}
+6
source

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 in an array

there are no options at all.
+2
source

Swift 5 Playground, .


# 1. as

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. compactMap(_:)

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. where is

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. filter(_:​)

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
 */
+2

flatMap [Int].

let a : [Any] = [5,"a",6]
for item in a.flatMap({ $0 as? Int }) {
    print(item)
}
0

Source: https://habr.com/ru/post/1607249/


All Articles