WWDC22 SALE: Save 50% on all my Swift books and bundles! >>

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?

1      

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
}

2      

ok, cool thanks @roosterboy

1      

Hacking with Swift is sponsored by Emerge

SPONSORED Optimize your app’s startup time, binary size, and overall performance using Emerge’s advanced app optimization and monitoring tools. Reliably measure app size, speed up your app's startup time with Emerge's Launch Booster, and much more. Emerge is actively used by many of the top mobile development teams in the world.

Find out more

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

Reply to this topic…

You need to create an account or log in to reply.

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.