“Is” type-casting pattern
By using the is operator in a case condition, you check if the value is a member of a particular type. One example where this would be useful would be parsing JSON you downloaded from a server. In case you’re not familiar, JSON is basically an array full of all different types, which you can write as [Any] in Swift.
Therefore you’ll need to check if each value is of a particular type:
let array: [Any] = [15, "George", 2.0]
for element in array { switch element { case is String:
print("Found a string") // 1 time default:
print("Found something else") // 2 times
}
}
With this code, you find out that one of the elements is of type String. But, you don’t have access to the value of that String in the implementation. That’s where the next pattern comes to the rescue.