2017-08-17 72 views
-1

我有一个字符串数组,我从网上拉任何颜色分类:Swift iOS - 如何按特定顺序排列数组?

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

,但它也可能出现如:

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

不管他们来这方式我想通过颜色的数组进行排序,并将其添加到一个新的数组,我希望新的阵列有这样的顺序:

//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" 
    } 
} 

我有一个例外:

fatal error: Index out of range

我知道我做的超出范围的错误,但我无法弄清楚如何得到它把它放在我想要的顺序。

如何循环访问颜色数组,并将其中的任何元素都按照我想要的顺序添加到新数组中?

回答

2

以下是一种可能的解决方案 - 根据实际颜色过滤主色列表。

let masterColors = ["red", "purple", "pink", "yellow", "brown", "blue", "orange", "green"] 
var colors = ["yellow", "red", "purple"] // whatever colors you have 
var newArr = masterColors.filter { colors.contains($0) } 
+0

感谢您的帮助!我会在15分钟后尝试并告诉你。 –

+0

按照你平常的ass!!有用 :) –