[Swift] Loop pattern matching by case-let

What is this article?

While reading Apple's sample code, I found a syntax I didn't see, so I looked it up.

Part of sample code


for case let foundObject as VNRecognizedObjectObservation in results {
    let bestLabel = foundObject.labels.first!	
    let objectBounds = foundObject.boundingBox
    print(bestLabel.identifier, bestLabel.confidence, objectBounds)	
}

I was interested in the first line. for case let foundObject as VNRecognizedObjectObservation in results I understand that iterating over the collection, but case let x as T was a mystery. By the way, this sample code is an image recognition app that uses the Vision framework. It seems that the detection results by Vision are lined up in results.

Cast only matching values

I ran the simplified code and saw it work.

Execution environment

Xcode 12.1 Swift 5.3 macOS 10.15.7

Arrays with inconsistent element types


let values: [Any] =  [ "1", 2, 3.4]

Process only for "values that can be cast to Int type" among the elements of the array


for case let number as Int in values {
    print(number)
}
// Prints 2

Consideration

If you just want to get the same execution result, there are likely to be various other approaches. However, there is only Apple's sample code, and I think that it is implemented with a very simple description.

Recommended Posts

[Swift] Loop pattern matching by case-let
[Swift] Event notification pattern
[Swift] Event notification by delegate