I'm in the process of making an app where the user will be quizzed on state capitals. The capital city and the state is presented to the user a UIImage and I have everything working properly. In an effort to reduce code, I am trying to figure out how to avoid all of these "if statements". The "if statements" below just represent four states and capital cities. Imagine these lines forty-six more times. That seems a bit much, right? I've come across Ternary Operators when studying algorithms and tried to use them to reduce this code, but I have had no success. I have two UIImage Arrays - one holds the cities, the other holds the states. The way that my app identifies if the user's answer is correct is matching the corresponding array indices.
Here are my abbreviated arrays ...
let capitalCityList: [UIImage] = [
UIImage(named: "Montgomery")!,
UIImage(named: "Juneau")!,
UIImage(named: "Phoenix")!,
UIImage(named: "Little Rock")!
let stateWordList: [UIImage] = [
UIImage(named: "Alabama")!,
UIImage(named: "Alaska")!,
UIImage(named: "Arizona")!,
UIImage(named: "Arkansas")!
Here are the first four "if statements" ...
if capitalCity.image == capitalCityList[0] && stateWord.image == stateWordList[0] {
scoreInt += 1
scoreLabel.text = String("Score: \(scoreInt)")
} else if capitalCity.image == capitalCityList[1] && stateWord.image == stateWordList[1] {
scoreInt += 1
scoreLabel.text = String("Score: \(scoreInt)")
} else if capitalCity.image == capitalCityList[2] && stateWord.image == stateWordList[2] {
scoreInt += 1
scoreLabel.text = String("Score: \(scoreInt)")
} else if capitalCity.image == capitalCityList[3] && stateWord.image == stateWordList[3] {
scoreInt += 1
scoreLabel.text = String("Score: \(scoreInt)")
} else if capitalCityWord.image == capitalCityList[4] && stateWord.image == stateWordList[4] {
scoreInt += 1
scoreLabel.text = String("Score: \(scoreInt)")