替换数组中的多次出现 - Swift 4.1

时间:2018-04-25 15:33:50

标签: arrays swift string replace swift-extensions

替换数组中的多次出现

Swift 4.1,Xcode 9.3

我希望为我Array的{​​{1}}扩展做一个扩展程序。

字符串扩展名:

String

用法:

public extension String {

    ///
    /// Replaces multiple occurences of strings/characters/substrings with their associated values.
    /// ````
    /// var string = "Hello World"
    /// let newString = string.replacingMultipleOccurrences(using: (of: "l", with: "1"), (of: "o", with: "0"), (of: "d", with: "d!"))
    /// print(newString) //"He110 w0r1d!"
    /// ````
    /// 
    /// - Returns:
    /// String with specified parts replaced with their respective specified values.
    /// 
    /// - Parameters:
    ///     - array: Variadic values that specify what is being replaced with what value in the given string 
    ///
    public func replacingMultipleOccurrences<T: StringProtocol, U: StringProtocol>(using array: (of: T, with: U)...) -> String {
        var str = self
        for (a, b) in array {
            str = str.replacingOccurrences(of: a, with: b)
        }
        return str
    }

}

我的尝试到目前为止与数组相同

var string = "Hello World"
let newString = string.replacingMultipleOccurrences(using: (of: "l", with: "1"), (of: "o", with: "0"), (of: "d", with: "d!"))
print(newString) //"He110 w0r1d!"

注意: 目前,此扩展程序造成了大量错误。

理想用法:

public extension Array {
    public func replacingMultipleOccurrences(using array: (of: Element, with: Element)...) -> Array {

        var newArr : Array<Element> = self
        var arr = array.filter { (arg) -> Bool in
            let (a, b) = arg
            return newArr.contains(a)
        }          
        for (i,e) in self.enumerated() {
            for (a,b) in arr {
                if e == a {
                    newArr[i] = b
                }
            }
        }
        return newArr
    }
}

我如何实现这一理想(最好以最有效的方式)?

3 个答案:

答案 0 :(得分:2)

extension Array where Element: Equatable {
func replacingMultipleOccurrences(using array: (of: Element, with: Element)...) -> Array {
    var newArr: Array<Element> = self

    for replacement in array {
        for (index, item) in self.enumerated() {
            if item == replacement.of {
                newArr[index] = replacement.with
            }
        }
    }

    return newArr
  }
}

答案 1 :(得分:2)

如果数组元素是Hashable,那么我会创建一个替换 首先是字典。然后可以有效地进行替换 单个遍历(使用map)和(快速)字典查找:

public extension Array where Element: Hashable {
    public func replacingMultipleOccurrences(using array: (of: Element, with: Element)...) -> Array {

        let replacements = Dictionary<Element, Element>(array, uniquingKeysWith: { $1 })
        return map { replacements[$0] ?? $0 }
    }
}

如果替换值恰好是a,这也可以正常工作 替换表后面的替换键。 例如:

let arr = [1, 2, 3, 2, 1]
let newArr = arr.replacingMultipleOccurrences(using: (of: 2, with: 3), (of: 3, with: 4))
print(newArr) // [1, 3, 4, 3, 1]

对于仅Equatable元素的数组,可以实现它 简明扼要地使用mapfirst(where:)

public extension Array where Element: Equatable {
    public func replacingMultipleOccurrences(using array: (of: Element, with: Element)...) -> Array {

        return map { elem in array.first(where: { $0.of == elem })?.with ?? elem }
    }
}

答案 2 :(得分:0)

我认为您应该使用map运算符。

extension String {
    func replace(mapping : [String : String]) -> String {
        return self.map { char -> String in  
            if let newValue = mapping[String(char)] {
                return newValue
            } else {
                return String(char)
            }
        }
    }
}