Passing and Casting Object Types in Swift

class TEST1 : NSObject  {

var name : String?
}
class TEST2 : NSObject  {

var name : String?
}
func compareObjects<T>(array1: [NSObject], array2: [NSObject], type:T.Type)  {

for objectA in array1  {
    let x = objectA as! T
    for objectB in array2{
        let y = objectA as! T
        if x.name == y.name {
            print("found a match")
            }
        }
     }
}

I don't think this is allowed. But if you all know a way to make it work it would be much appreciated. it'll save me a lot of duplicate code.

Upvotes: 0

Views: 167

Answers (1)

Mr. A
Mr. A

Reputation: 714

Why you do that? You can simply implement Hashable protocol and override == operator to compare two objects. Then you can simply write: x == y without any loops.

Upvotes: 1

Related Questions