1

Need to compare the two array, array1 = [1,2,3,4] array2 = [1,5,6,7,8] Result should in bool value.Need to check whether the array1 contain any similar element in array2. So someone help me to solve the above problem.

Jananni M
  • 41
  • 6

2 Answers2

2

Maybe this way will suit your needs:

let array1 = [1,2,3,4], array2 = [1,5,6,7,8]
let set1 = Set<Int>(array1), set2 = Set<Int>(array2)
let containsSimilar = set1.intersection(set2).count > 0

Edit based on comments

let array1: [Any] = [1,2,"a"], array2: [Any] = ["a","b","c"]
let set1 = Set<JananniObject>(array1.flatMap({ JananniObject(any: $0) }))
let set2 = Set<JananniObject>(array2.flatMap({ JananniObject(any: $0) }))
let containsSimilar = set1.intersection(set2).count > 0

Where JananniObject is:

enum JananniObject: Equatable, Hashable {

    case integer(Int)
    case string(String)

    static func ==(lhs: JananniObject, rhs: JananniObject) -> Bool {
        switch (lhs, rhs) {
        case (.integer(let integer0), .integer(let integer1)):
            return integer0 == integer1
        case (.string(let string0), .string(let string1)):
            return string0 == string1
        default:
            return false
        }
    }

    var hashValue: Int {
        switch self {
        case .integer(let integer):
            return integer.hashValue
        case .string(let string):
            return string.hashValue
        }
    }

    init?(any: Any) {
        if let integer = any as? Int {
            self = .integer(integer)
        } else if let string = any as? String {
            self = .string(string)
        } else {
            return nil
        }
    }
}
iWheelBuy
  • 5,470
  • 2
  • 37
  • 71
0

You can do this using Set:

let one = [1, 2, 3]
let two = [2, 1, 3]
let three = [2, 3, 4]

print(Set(one).isSubset(of: two)) // true
print(Set(one).isSubset(of: three)) // false
pacification
  • 5,838
  • 4
  • 29
  • 51