adams.s adams.s - 5 months ago 19
Swift Question

Possibilities Array's (swift)

How can i use more values of an array in a swift statement?

code:

var array = ["Beer", "Water", "Cola", "Sprite", "Wodka"]

var drinks = "" // The variable drinks updates with a pickerView of the above array

func doSomethingWithArray() {

if drinks == array[1] {

print("this is water, so no sugar in it")

} else if drinks == array[2,3] {

print("This drink contains sugar")

} else {
print("This drink is alcoholic")
}


Is there an easy way to use multiple array values like in the else if statement? but a way that works then. :)

Answer

After following the conversation in the comments, this code should work

struct Drink {
    var name: String
    var haveSugar: Bool
    var haveAlcohol: Bool

    init (name: String, haveSugar: Bool, haveAlcohol: Bool) {
        self.name = name
        self.haveSugar = haveSugar
        self.haveAlcohol = haveAlcohol
    }
}

var drinks = [Drink(name: "Beer", haveSugar: true, haveAlcohol: true), Drink(name: "Water", haveSugar: false, haveAlcohol: false), Drink(name: "Sprite", haveSugar: true, haveAlcohol: false), Drink(name: "Wodka", haveSugar: true, haveAlcohol: true)]

func checkDrink(drink: Drink) {
    if drink.haveSugar == true {
        print("\(drink.name) have sugar!")
    }
    else {
        print("\(drink.name) doesn't have sugar")
    }
}

checkDrink(drinks[1])
Comments