4

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

2 Answers 2

7

Try this:

for result in results as [XYZClass] {
    // Do stuff to result
}
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.