gpt4 book ai didi

ios - 可能性数组的(快速)

转载 作者:行者123 更新时间:2023-11-29 00:54:49 25 4
gpt4 key购买 nike

如何在 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 语句中那样使用多个数组值的简单方法?但这是一种可行的方法。 :)

最佳答案

如果我理解你的问题是正确的,在这种情况下你可以使用 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"]

关于ios - 可能性数组的(快速),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37707491/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com