Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 432
SuPotter Avatar asked Feb 11 '23 10:02

SuPotter


2 Answers

Try this:

for result in results as [XYZClass] {
    // Do stuff to result
}
like image 112
Daniel T. Avatar answered Feb 20 '23 15:02

Daniel T.


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.

like image 27
Aron Avatar answered Feb 20 '23 17:02

Aron