4

Replacing Multiple Occurrences in Array

Swift 4.1, Xcode 9.3

I want to make an extension alike an extension I made for Array for String.


String Extension:

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
    }

}

Usage:

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!"

My Attempt So Far for the Same Thing with an Array

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

Note: currently, this extension is creating a ton of errors.

Ideal Usage:

let arr = [1,2,3,4,5,6,7,8,9]
let newArr = arr.replacingMultipleOccurrences(using: (of: 2, with: 20), (of: 3, with: 30), (of: 5, with: 50), (of: 8, with: 80), (of: 9, with: 90))
print(newArr) //[1,20,30,4,50,6,7,80,90]

How do I accomplish this ideal (preferably in the most efficient way possible)?

Community
  • 1
  • 1
Noah Wilder
  • 1,656
  • 20
  • 38

3 Answers3

3
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
  }
}
Tom Pearson
  • 384
  • 1
  • 8
  • 1
    Note that `[1, 2, 3].replacingMultipleOccurrences(using: (of: 2, with: 3), (of: 3, with: 4))` would return `[1, 4, 4]` with that approach, that might be unexpected. – Martin R Apr 30 '18 at 07:00
  • Shouldn't this conform to `Equatable` rather than `Comparable`? – Noah Wilder May 17 '18 at 12:51
3

If the array elements are Hashable then I would create a replacement dictionary first. Then the substitution can be done efficiently with a single traversal (using map) and a (fast) dictionary lookup:

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

This also works correctly if a replacement value happens to be a replacement key later in the substitution table. Example:

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]

For arrays of just Equatable elements it can be implemented succinctly using map and first(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 }
    }
}
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
0

I think you should use the map operator.

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)
            }
        }
    }
}
Noah Wilder
  • 1,656
  • 20
  • 38
CZ54
  • 5,488
  • 1
  • 24
  • 39