如果swift

时间:2018-01-21 02:10:24

标签: arrays swift

我正在使用一些Swift代码来运行字符串(团队)数组,如果存在来自另一个数组(charsToRemove)的特殊字符,请从teams数组中删除该项。或者,我也可以将不包含特殊字符的项目添加到数组中。以下是一些示例数据:

teams = ["lime", "teal/gold", "red-2", "orange", "orange(6)", "blue-7" ... ]
charsToRemove = [ "(", ")", "-", " ", "/" ... ]

最终结果如下:

teams = ["lime", "orange"]

我已经尝试了几次循环迭代,但寻找可能是最佳路线。团队数组和特殊字符有点长,但不想在这里粘贴太多。

3 个答案:

答案 0 :(得分:1)

您可以使用String方法rangeOfCharacter(from: CharacterSet)来检查它是否找到了一系列字符集并使用它来过滤您的数组:

let teams = ["lime", "teal/gold", "red-2", "orange", "orange(6)", "blue-7"]
let charsToRemove = [ "(", ")", "-", " ", "/" ]
let cs = CharacterSet(charactersIn: charsToRemove.joined())
let filtered = teams.filter({ $0.rangeOfCharacter(from: cs) == nil })
print(filtered)   // ["lime", "orange"]

答案 1 :(得分:0)

您可以在Array上使用单个filter操作。在过滤器内部,您只需致电charsToRemove.contains(where:)以检查teamName是否包含charsToRemove的任何元素,如果不是,请将团队名称保留在已过滤的数组中

let teams = ["lime", "teal/gold", "red-2", "orange", "orange(6)", "blue-7" ]
let charsToRemove = [ "(", ")", "-", " ", "/"]
let filteredTeams = teams.filter({ teamName -> Bool in
    charsToRemove.contains(where: { teamName.contains($0) }) == false
})

答案 2 :(得分:0)

Leo's answer的更可重用(更清晰的恕我直言)方法是扩展Array

extension Array where Element == String {
    /// Returns a new array after applying the filter
    var cleaned: [Element] {
        let charSet = CharacterSet(charactersIn: " ()-/") // note the space
        return filter { $0.rangeOfCharacter(from: charSet) == nil }
    }
}

let teams = ["lime", "teal/gold", "red-2", "orange", "orange(6)", "blue-7"]
print(teams.cleaned) // prints: ["lime", "orange"]

如果您想扩大其应用程序,请扩展Sequence

extension Sequence where Element == String {
    /// Returns a new array after applying the filter
    var cleaned: [Element] {
        let charSet = CharacterSet(charactersIn: " ()-/") // note the space
        return filter { $0.rangeOfCharacter(from: charSet) == nil }
    }
}

let teams = ["lime", "teal/gold", "red-2", "orange", "orange(6)", "blue-7"]
print(teams.cleaned) // prints: ["lime", "orange"]

let set = Set(teams)
print(set.cleaned) // prints: ["orange", "lime"]

(注意:Set未订购)