0

I have struct model like

struct ModelA {
    let text: String
    let id: Int
}

extension ModelA: Equatable {}

func ==(lhs: ModelA, rhs: ModelA) -> Bool {
    let areEqual = lhs.id == rhs.id
    return areEqual
}

i have created arrays of this model

let a1:[ModelA] = [ModelA(text: "10", id: 11), ModelA(text: "11", id: 12)]
let a2:[ModelA] = [ModelA(text: "11", id: 12)]

and having a comparing function

func isEqualArray(first array1: [Any], second array2: [Any]) -> Bool {
     let set1 = NSSet(array: array1)
     let set2 = NSSet(array: array2)
     return set1.isSubset(of: set2 as! Set<AnyHashable>)
}

so when i'm trying to cross check

 let flag = isEqualArray(first: a1, second: a2)
 print("### \(flag)")

It crashes on function return

enter image description here

What am I doing wrong?

2
  • Your struct needs to conform to hashable as well as equatable Commented Aug 3, 2017 at 3:54
  • why are you using NSSet instead of Swift sets? And any time you use ! you are asking for your code to crash if the downcast fails. Commented Aug 3, 2017 at 3:55

1 Answer 1

1

Your struct needs to conform to both equatable and hashable in order to be used in a Set. It seems that you only care about the id, so a simple implementation would be:

struct ModelA {
    let text: String
    let id: Int
}

extension ModelA: Equatable {
    static func ==(lhs: ModelA, rhs: ModelA) -> Bool {
        return lhs.id == rhs.id
    }
}

extension ModelA: Hashable {
    var hashValue: Int {
        return id
    }
}

Now, you can use Swift sets in your isEqualArray function; you also need to consider which set is smaller since you are using isSubSet(of:):

func isEqualArray(first array1: [AnyHashable], second array2: [AnyHashable]) -> Bool {

    let set1: Set<AnyHashable>
    let set2: Set<AnyHashable>

    if array1.count > array2.count {
        set1 = Set(array1)
        set2 = Set(array2)
    } else {
        set1 = Set(array2)
        set2 = Set(array1)
    }
    return set2.isSubset(of: set1)
}

Your code actually determines if one array is a subset of another, not if the arrays are equal, so I am not sure if that is what you want.

Sign up to request clarification or add additional context in comments.

1 Comment

As I said, your code is using isSubSet(Of:), so you need to know which array is larger, a larger set cannot be a subset of a smaller set

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.