Daniel Dramond Daniel Dramond - 4 years ago 65
Swift Question

How to know if a set certain amount of strings match in 2 arrays

I have a simple line of code with 2 String Arrays. They both contain the same strings inside both arrays and I have an if statement that will work if both arrays are the same. Like so:

var firstArray: [String] = ["Music", "Art", "Sports", "Movies"]
var secondArray: [String] = ["Music", "Art", "Sports", "Movies"]

if firstArray == secondArray {

//they match...

However, I want to be able to add a few more strings to the first array so the 2 arrays aren't fully the same, which will cancel out the if statement above BUT I want to run the if statement if 4 or more strings are the same in the second array as they are in the first array. How do I do this? Thank you.

Answer Source

You can find the size of the intersection between the two arrays:

let firstArray = ["Music", "Art", "Sports", "Movies"]
let secondArray = ["Music", "Art", "Sports", "Movies"]

if firstArray == secondArray {

if Set(firstArray).intersection(secondArray).count >= 4 {
    print("At least 4 are equal")

Keep in mind that converting an Array to a Set is a O(n) operation. If you're doing this often, cache the Set rather than recomputing it on every check.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download