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

SOLVED: Day 54 Project 11, Part 2 - Add a custom star rating component

Forums > 100 Days of SwiftUI

Why do we need to declare var offImage: Image? and use it in func image(for:)? We do not assign any value to it and it seems to be working just fine without it. If this is just for flexibility so that you can adjust the code to the below and in this case you just see number of stars equal to your rating i.e if you have 3 stars only three are displayed and not like 3 stars highlighted and 2 greyed out:

func image(for number: Int) -> Image? {
        if number > rating {
            return offImage
        } else {
            return onImage
        }
    }

Maybe it is needed later in the project, but currently it doesn't make any sense for me... Any hint appreciated :)

2      

It's to give you flexibility to use different images for on and off.

If you set offImage to something, the rating will use that image for the off value; if you don't assign anything, offImage is nil and the rating will use the onImage instead. And then those images get colored using onColor or offColor.

For instance, you could set offImage to this, say in your app's settings screen after the user changes how they want to see that image:

Image(systemName: "star.slash.fill")

and then you would see this:

ratings different offImage

5      

Thanks @roosterboy! So that what I was thinking about, it's for flexibility. Initially, it confused me a bit as it was not utilized in the code, so the purpose was not clear and no mentioning about it in the video as well.

2      

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.