UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: day 15: optional downcasting in array

Forums > 100 Days of Swift

for album in allAlbums as? [LiveAlbum] ?? [LiveAlbum]() {
    print("Running?")
    print(album.location)
}

hi, the loop does not print anything.

Initially, i thought the for loop will check whether each array element in allAlbums is LiveAlbum or not. And if it is true, it executes the code within the for loop. But, it seems this is not true from my testing.

Is the array statement checking whether ALL array elements are LiveAlbum subclass? And only if they are ALL LiveAlbum subclass, the code within the for loop gets executed?

3      

Is the array statement checking whether ALL array elements are LiveAlbum subclass? And only if they are ALL LiveAlbum subclass, the code within the for loop gets executed?

Yep. That's why you have to supply [LiveAlbum]() with nil coalescing in case the cast fails; you are attempting to typecast the entire array at once and need something there in case it fails.

If you wanted to just print the items in allAlbums which are a LiveAlbum, you could do this:

for album in allAlbums where album is LiveAlbum {
    //this acts as a filter but doesn't typecast album,
    //so we have to cast inside the loop
    print((album as! LiveAlbum).location) //force cast is safe here
}

4      

ok, cool thanks @roosterboy

3      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.