TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

SOLVED: Can someone please help pe understand why a function is written?

Forums > SwiftUI

@Sanda  

I am at 100 days of swiftUI, day 54.


import SwiftUI

struct RatingView: View {
    @Binding var rating: Int

    var offImage: Image?
    var onImage = Image(systemName: "star")

    var offColor = Color.gray
    var onColor = Color.yellow

    var body: some View {
        HStack{

            ForEach(1..<6 , id: \.self){number in
                image(for: number)
                    .foregroundStyle(number > rating ? .gray : .yellow)
                    .onTapGesture {
                        rating = number
                    }
            }
        }
    }
    func image(for number: Int) -> Image {
        if number > rating {
            return offImage ?? onImage
        } else {
            return onImage
        }
    }
}

#Preview {
    RatingView(rating: .constant(4))
}

this is the code explained in the course. I cant understand why we used offImage and image function. Why can't i use onImage directly in ForEach like this:

ForEach(1..<6 , id: \.self){number in
                onImage
                    .foregroundStyle(number > rating ? .gray : .yellow)
                    .onTapGesture {
                        rating = number
                    }
            }

I understood that offImage will always be nil and image function will alwais return onImage, am I wrong?

2      

Hacking with Swift is sponsored by Blaze.

SPONSORED Still waiting on your CI build? Speed it up ~3x with Blaze - change one line, pay less, keep your existing GitHub workflows. First 25 HWS readers to use code HACKING at checkout get 50% off the first year. Try it now for free!

Reserve your spot now

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.