从数组中删除一些元素

时间:2017-07-15 14:29:34

标签: arrays swift string swift3

我有以下情况需要从数组中删除一些元素。我有一个包含以下元素的数组:

[
    "white & blue", "white & red", "white & black", 
    "blue & white", "blue & red", "blue & black", 
    "red & white", "red & blue", "red & black", 
    "black & white", "black & blue", "black & red", 
    "white", "blue", "red", "black", 
    "white & blue & red & black"
] 

我需要将其转换为只包含这些元素的数组:

[
    "white & blue", "white & red", "white & black", 
    "blue & red", "blue & black", 
    "red & black", 
    "white", "blue", "red", "black", 
    "white & blue & red & black"
]

在上面的示例中,元素"white & blue""blue & white"需要被视为相同,只保留其中一个并删除另一个。

我还没有找到一种有效的方法。我怎么能这样做?

1 个答案:

答案 0 :(得分:2)

对于等同描述为:“white& blue”和“blue& white”元素需要被视为相同的,为Set定义的等式效果很好

准备:

extension String {
    var colorNameSet: Set<String> {
        let colorNames = self.components(separatedBy: "&")
            .map {$0.trimmingCharacters(in: .whitespaces)}
        return Set(colorNames)
    }
}

"white & blue".colorNameSet == "blue & white".colorNameSet //== true

(假设每个元素中每个颜色名称最多出现一次。)

还有一个Set,从数组中删除重复项时,Set非常有用。

removing duplicate elements from an array

所以,你可以这样写:

let originalArray = [
    "white & blue", "white & red", "white & black", "blue & white",
    "blue & red", "blue & black", "red & white", "red & blue",
    "red & black", "black & white", "black & blue", "black & red",
    "white", "blue", "red", "black", "white & blue & red & black"]

func filterDuplicateColorNameSet(_ originalArray: [String]) -> [String] {
    var foundColorNameSets: Set<Set<String>> = []
    let filteredArray = originalArray.filter {element in
        let (isNew,_) = foundColorNameSets.insert(element.colorNameSet)
        return isNew
    }
    return filteredArray
}

print(filterDuplicateColorNameSet(originalArray))
//->["white & blue", "white & red", "white & black", "blue & red", "blue & black", "red & black", "white", "blue", "red", "black", "white & blue & red & black"]