3

I am a newbie when it comes to programming and just started learning Swift. Your help would be appreciated for the below array concept I am trying to work out.

How can I make the below coding shorter so that I can reduce the amount of If Statements. So when a "battlename = name[0]" index is selected the statement automatically selects the corresponding monsters at the same index level without having to use so many If statements.

Hope I'm making sense.

var names = ["Lancelot", "Arthur", "Gawain", "Galahad"]
var monsters = ["Dragon", "Boar", "Giant", "Griffin"]
let battlename = names[1]
print(battlename, "Vs.", monsters)

if battlename == names[0] {
print(battlename, "Vs.", monsters[0])
}
else if battlename == names[1] {
print(battlename, "Vs.", monsters[1])
}
else if battlename == names[2] {
print(battlename, "Vs.", monsters[2])
}
else if battlename == names[3] {
print(battlename, "Vs.", monsters[3])
}

2 Answers 2

7

You can replace all your conditions with this single one:

if let index = names.indexOf(battlename) {
    print(battlename, "Vs.", monsters[index])
}

Also, a tip if you want to print the list of the monsters names in your intro, instead of just printing the array you can join the items as a string:

print(battlename, "Vs.", monsters.joinWithSeparator(", ")) // "Arthur Vs. Dragon, Boar, Giant, Griffin"
Sign up to request clarification or add additional context in comments.

Comments

0
    var names = ["Lancelot", "Arthur", "Gawain", "Galahad"]
    var monsters = ["Dragon", "Boar", "Giant", "Griffin"]
    let battlename = names[1]

    var index = names.indexOf(battlename)
    if index != nil
    {
        print(battlename, "Vs.", monsters[index!])
    }
    else
    {
        print("No match")
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.