Swift iOS-如何按特定顺序对数组进行排序?

时间:2017-08-17 19:10:36

标签: ios arrays swift sorting

我有一系列字符串,我从网上以各种颜色提取:

var colors = ["red", "green", "yellow", "blue", "purple"]

但它也可能会出现:

//this time less colors
var colors = ["yellow", "red", "purple"]

无论他们进入哪个方向,我都希望对colors数组进行排序并将它们添加到新数组中,我希望新数组具有以下顺序:

//the way I want the new array to have it's elements
["red", "purple", "pink", "yellow", "brown", "blue", "orange", "green"]

我试过了:

var newArr:[String] = []

for color in colors{

  if color == "red"{
    newArr[0] = "red"
  }
  if color == "purple"{
    newArr[1] = "purple"
  }
  if color == "pink"{
    newArr[2] = "pink"
  }
  if color == "yellow"{
    newArr[3] = "yellow"
  }
  if color == "brown"{
    newArr[4] = "brown"
  }
  if color == "blue"{
    newArr[5] = "blue"
  }
  if color == "orange"{
    newArr[6] = "orange"
  }
  if color == "green"{
    newArr[7] = "green"
  }
}

我有一个例外:

  

致命错误:索引超出范围

我知道我在哪里犯了超出范围的错误,但我无法弄清楚如何让它按照我想要的顺序排列。

如何循环使用colors数组并获取其中的任何元素,并按照我想要的顺序将它们添加到新数组中?

1 个答案:

答案 0 :(得分:3)

这是一个可能的解决方案 - 根据您实际拥有的颜色过滤主色列表。

C