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) }
With Swift 5, you can choose one of the following Playground sample codes in order to solve your problem.
as
type-casting patternlet array: [Any] = [5, "a", 6]
for case let item as Int in array {
print(item) // item is of type Int here
}
/*
prints:
5
6
*/
compactMap(_:)
methodlet array: [Any] = [5, "a", 6]
for item in array.compactMap({ $0 as? Int }) {
print(item) // item is of type Int here
}
/*
prints:
5
6
*/
is
type-casting patternlet array: [Any] = [5, "a", 6]
for item in array where item is Int {
print(item) // item conforms to Any protocol here
}
/*
prints:
5
6
*/
filter(_:)
methodlet array: [Any] = [5, "a", 6]
for item in array.filter({ $0 is Int }) {
print(item) // item conforms to Any protocol here
}
/*
prints:
5
6
*/