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

Day 19: Not sure how UIImage is using an array of strings to pull images

Forums > 100 Days of Swift

We have this code for the flag game project:

func askQuestion() {
      button1.setImage(UIImage(named: countries[0]), for: .normal)
      button2.setImage(UIImage(named: countries[1]), for: .normal)
      button3.setImage(UIImage(named: countries[2]), for: .normal)
  }

My confusion is this: according to the code, it seems button1 is "setting its image" to the output of UIImage's "named: countries[0]"

However, countries[0] is simply a string. How is the system getting an image out of it? Is it checking the assets for an image whose title matches the string in countries[0]?

Additionally, if I added a random string into countries like "Zebras", would UIImage be able to pull an image out of it as well even though it doesn't exist?

Trying to get a conceptual grasp of this code...

3      

How is the system getting an image out of it? Is it checking the assets for an image whose title matches the string in countries[0]?

Yep.

Additionally, if I added a random string into countries like "Zebras", would UIImage be able to pull an image out of it as well even though it doesn't exist?

Nope. How would the system create an image if it doesn't exist in your assets?

4      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

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.