如何在swift中删除数组中的单词?

时间:2017-11-13 21:13:48

标签: swift

我有以下变量:

var fruits = ["Apple", "Apricot", "Banana", "Blueberry", "Cantaloupe", "Cherry","Clementine", "Coconut"]

对于任何这些水果,我有另一个变量:apple = 1或0,appricot = 1或0 ...

我的问题是如何制作,例如,如果apple == 1,“Apple”这个词就在列表中?如果apple == 0,我的列表将是:

var fruits = [ "Apricot", "Banana", "Blueberry", "Cantaloupe", "Cherry","Clementine", "Coconut"]

2 个答案:

答案 0 :(得分:1)

  • 要从您的阵列中删除元素,您只需使用fruits.remove(at: [index])

因此,在您的示例中,它看起来像这样:

var fruits = ["Apple", "Apricot", "Banana", "Blueberry", "Cantaloupe", "Cherry","Clementine", "Coconut"]
var apple = 0

if apple == 0 {
    fruits.remove(at: 0) //remove 0th index in your array, which is "Apple"
}
  • 要以更安全的方式接近它,您可以使用fruits.filter { $0 != "[fruit name]" }。这将保留原始数组,并创建一个新数组。

它看起来像这样:

var fruits = ["Apple", "Apricot", "Banana", "Blueberry", "Cantaloupe", "Cherry","Clementine", "Coconut"]
var fruits2 = fruits
var apple = 0

if apple == 0 {
    fruits2 = fruits.filter { $0 != "Apple" }
}

答案 1 :(得分:0)

如果我理解你的问题,你希望水果数组 Apple 如果apple == 1或者没有 Apple 的水果数组。您可以使用以下代码。如果我不理解这个问题并且这不是您想要达到的目标,请发布更多代码并更明确。

 var fruits : [String] = []

        if apple == 0 {
         fruits = [ "Apricot", "Banana", "Blueberry", "Cantaloupe", "Cherry","Clementine", "Coconut"]
        } else {
        fruits = ["Apple"]
        }

稍后编辑:

好的,所以我更了解你的问题。你想构建一个水果数组,如果水果的变量是1,你想要它在数组中。

首先,您必须使用Bool类型的变量而不是Int

您可以使用2个数组,一个包含Boolfruits变量。匹配其索引,例如fruitsIncluded[0]将匹配fruits[0],在您的情况下为"Apple"。然后创建一个最终的水果数组(finalArrayOfFruits),其中你有水果true

var fruits = [ "Apple", "Apricot", "Banana", "Blueberry", "Cantaloupe", "Cherry","Clementine", "Coconut"]
var fruitsIncluded = [true, false, false, true, false, true, true, false]

var finalArrayOfFruits : [String] = []

for i in 0..<fruits.count {
if fruitsIncluded[i] {
finalArrayOfFruits.append(fruits[i])
}
}