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

Day 25 - Rock Paper Scissors - Trying to show only 2 options

Forums > 100 Days of SwiftUI

Hello!

Basically i'm trying to display two options for the user by omitting the app's current choice e.g. app chose rock, i omit that button from the UI and only show paper and scissors

I can do this easily and have created a function that returns a new "options" array of ["Paper", "Scissors"]. Here is my code for displaying these buttons

    private func optionsToDisplay() -> some View {
        let index = options.firstIndex(of: options[randomOption])!
        var newOptions = self.options
        newOptions.remove(at: index)
        return ForEach(newOptions, id: \.self) { option in
            Button(action: {
                self.checkResult(selected: option)
            }) {
                Text(option)
            }
        }
    }

My question is - is it dodgy that i'm displaying a dynamically calculated array but I'm using id: self? I feel like it is but I can't figure out the words to google to find out for myself.

I think it's dodgy because newOptions doesn't exist on self - it's calculated dynamically... so then why does it work?

Any ideas?

2      

\.self here refers to the items in the collection passed into ForEach, not the enclosing View object like self two lines above. Note the \. in front; this means it's a keypath rather than the self keyword. Essentially, this is saying that the id for the objects being looped over is each object itself, because newOptions is some type that conforms to the Identifiable protocol.

In short, it's not dodgy at all. Using the \.self keypath is correct.

5      

Absolute legend, thanks @roosterboy ! Understand it better now

2      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

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.