需要比较两个数组, array1 = [1,2,3,4] array2 = [1,5,6,7,8] 结果应该在bool值中。需要检查array1是否包含array2中的任何类似元素。所以有人帮我解决了上述问题。
答案 0 :(得分: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
}
}
}
答案 1 :(得分:0)
您可以使用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