需要比较两个数组,数组 1 = [1,2,3,4]数组 2 = [1,5,6,7,8]结果应为布尔值。需要检查数组 1 是否包含数组 2 中的任何类似元素。所以有人帮我解决了上述问题。
也许这种方式将满足您的需求:
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
根据评论进行编辑
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
JananniObject
在哪里:
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
}
}
}
您可以使用
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