SuPotter
SuPotter

Reputation: 764

Type cast array elements in for loop

In a delegate method, I get back a ‘results’ array of a custom object type, and I want to loop through the array elements. I do the following now, and this works

for result in results {
    if result is XYZClass {     
        //This Works!    
    }
}

Is there a way to type cast the objects in the for-loop to avoid writing two lines? Does swift permit this? Used to get this done fairly easily in Objective - C

for (XYZClass *result in results) {

}

However, I have not been successful in Swift. I’ve tried explicit-cast with no luck.

for result as XYZClass in results {
    //ERROR: Expected ‘;’ in ‘for’ statements
}

for result:AGSGPParameterValue in results {
    /* ERROR: This prompts down cast as 
    for result:AGSGPParameterValue in results as AGSGPParameterValue { }
    which in turn errors again “Type XYZClass does not conform to Sequence Type”
*/
}

Any help is appreciated

Upvotes: 4

Views: 2618

Answers (2)

Aron
Aron

Reputation: 3571

Depending on how you are using the for loop it may be instead preferable to use compactMap (or flatMap if you are before Swift 4.1) to map your objects into a new array:

let onlyXyzResults: [XYZClass] = results.compactMap { $0 as? XYZClass }

Now you have an array XYZClass objects only, with all other object types removed.

Upvotes: 1

Daniel T.
Daniel T.

Reputation: 33967

Try this:

for result in results as [XYZClass] {
    // Do stuff to result
}

Upvotes: 7

Related Questions