如何在swift语句中使用更多数组值?
代码:
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")
}
是否有一种简单的方法可以在else if语句中使用多个数组值?但那是一种有效的方式。 :)
答案 0 :(得分:1)
如果我理解你的问题是正确的,那么就可以使用contains
。
let myDrink = "Cola"
let sweetDrinks = ["Cola", "Sprite"]
if sweetDrinks.contains(myDrink) {
print(myDrink, "is a sweet drink")
}
要进行更复杂的检查,请使用Set。例如:
let myDrinks = Set(["Beer", "Water", "Cola", "Vodka", "Tonic"])
let sweetDrinks = ["Cola", "Sprite", "Tonic"]
// Show myDrinks which are also sweet drinks
let mySweetDrinks = myDrinks.intersect(sweetDrinks)
print(mySweetDrinks) // prints ["Tonic", "Cola"]
答案 1 :(得分:0)
在评论中跟踪对话之后,此代码应该可以正常工作
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])