swiftstringduplicateslines

How to remove duplicates of lines of a String in Swift without lost their order?


I would like to remove duplicates of lines in a string with Swift 3. I got to do it but unfortunately at the end of the process the lines lost the order. Here is my code:

// string with 7 lines and 2 duplicates (MacBook and Mac mini)
var str = "MacBook\nMacBook Pro\nMacPro\nMacBook\niMac\nMac mini\nMac mini"

var components = str.components(separatedBy: .newlines)
print(components)

// remove duplicates: first by converting to a Set
// and then back to Array (found in iSwift.org)
components = Array(Set(components))
print(components)

let newStr = components.joined(separator: "\n")
print(newStr)

EDIT: When removing duplicates, I prefer to keep the first one not the last one.


Solution

  • Tweaking @LeoDabus' comment…

    let str = "MacBook\nMacBook Pro\nMacPro\nMacBook\niMac\nMac mini\nMac mini"
    let components = str.components(separatedBy: .newlines)
    
    let depDuped = components.reduce([]) {
        $0.0.contains($0.1) ? $0.0 : $0.0 + [$0.1]
    }.joined(separator: "\n")
    

    If duplicates can occur elsewhere in the string (so "A\nB\nA" would be unchanged), then

    let depDuped = components.reduce([]) {
        $0.0.last == $0.1 ? $0.0 : $0.0 + [$0.1]
    }.joined(separator: "\n")