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
Try this:
for result in results as [XYZClass] {
// Do stuff to result
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With