How to use 'difference(from:' method

Hello. I have a little example of how I would use the difference(from:, but it does not work as I expect.

 let exists = ["Cat", "Dog", "Mouse"]
 let incom = ["Cat", "Dog", "Mouse", "Fish"]
 let dif = incom.difference(from: exists)
 let answer1 = dif.contains("Fish") // Cannot convert value of type 'String' to expected argument type 'CollectionDifference<String>.Element' (aka 'CollectionDifference<String>.Change')
 let answer2 = dif.inferringMoves().contains("Fish") // Cannot convert value of type 'String' to expected argument type 'CollectionDifference<String>.Element' (aka 'CollectionDifference<String>.Change')

Please, explain, for what this method was created.

Does this help?

The result is not an array of elements, but an array of instructions about how to get to those elements.

It's an implementation of Myers's Diffing Algorithm

import Foundation

let exists = ["Cat", "Dog", "Mouse"]
let incom = ["Cat", "Dog", "Mouse", "Fish"]
let diff = incom.difference(from: exists)
print(type(of: diff))
diff.forEach { print($0) }

gives:

CollectionDifference<String>
insert(offset: 3, element: "Fish", associatedWith: nil)

1 Like