Segmented control isn't changing to the selected index

So I'm making a game, and I have a segmented control for the user to select a difficulty level. Inside the cases for the control, I wrote some simple code to see if the difficulty changes when the user selects a different segment. Here it is:

@IBAction func chooseOnePlayerDifficulty(_ sender: UISegmentedControl) {
    switch onePlayerGameType {
        case .sluggish:
            onePlayerGameType = typeOfGame.sluggish
            print("Sluggish difficulty selected")
        case .average:
            onePlayerGameType = typeOfGame.average
            print("Average difficulty selected")
        case .ninja:
            onePlayerGameType = typeOfGame.ninja
            print("Ninja game mode selected")
    }
}

When I test it and select different segments, the only thing that shows up in the console is "Average difficulty selected."

Why isn't it changing and how can I fix it?

What type is this method defined in and how is the typeOfGame declared?

What do you mean by this?

Also, typeOfGame is declared as:

enum typeOfGame {
case sluggish
case average
case ninja

}

Is the problem that the UISegmentedControl is not reflecting taps on different segments or that onePlayerGameType isn’t updated when the user taps a different segment? If the former, the problem might be isEnabled or isUserInteractionEnabled being set to false, either in code or in Interface Builder. If the latter, the problem is that you are not using selectedSegmentIndex. See the following for an example of how to do so: Conjugar/BrowseInfoVC.swift at master · vermont42/Conjugar · GitHub

What would I replace the values browseInfoView and difficultyControl with?

You probably want to update the value of onePlayerGameType before (and not in) the switch based on the value of the selectedSegmentIndex. Something like this:

@IBAction func chooseOnePlayerDifficulty(_ sender: UISegmentedControl) {
    guard let selectedGameType = typeOfGame(rawValue: sender.selectedSegmentIndex) else {
       fatalError("no corresponding game type for the index selected by the segmented control")
    }

    onePlayerGameType = selectedGameType

    switch onePlayerGameType {
        case .sluggish:
            print("Sluggish difficulty selected")
        case .average:
            print("Average difficulty selected")
        case .ninja:
            print("Ninja game mode selected")
    }
}

For this to work, the typeOfGame enum would have to be declared to have an Int raw value and the cases would need to be in the same order as your segmented control:

enum typeOfGame: Int {
    case sluggish, average, ninja
}
1 Like

let index = sender.selectedSegmentIndex

Then set onePlayerGameType based in index, which has values 0, 1, or 2, assuming that the number of segments is 3.

Thanks, this worked. One more question, how would I retrieve the selected game type in the start button?