Ger*_*ski 39 arrays swift swift2
假设有两个阵列......
var array1 = ["a", "b", "c"]
var array2 = ["b", "c", "a"]
Run Code Online (Sandbox Code Playgroud)
我希望这两个数组的比较结果是真的,以下是......
var array1 = ["a", "b", "c"]
var array2 = ["b", "c", "a", "d"]
Run Code Online (Sandbox Code Playgroud)
......是假的 我怎样才能在Swift中实现这一目标?我试图将两个数组转换为集合,但由于某种原因,Set()不断删除数组包含的一些(通常是重复的)对象.
任何帮助,将不胜感激.
Ale*_*loz 70
斯威夫特3,4
extension Array where Element: Comparable {
func containsSameElements(as other: [Element]) -> Bool {
return self.count == other.count && self.sorted() == other.sorted()
}
}
// usage
let a: [Int] = [1, 2, 3, 3, 3]
let b: [Int] = [1, 3, 3, 3, 2]
let c: [Int] = [1, 2, 2, 3, 3, 3]
print(a.containsSameElements(as: b)) // true
print(a.containsSameElements(as: c)) // false
Run Code Online (Sandbox Code Playgroud)
小智 9
斯威夫特 5.2 解决方案
var array1 = ["a", "b", "c"]
var array2 = ["b", "c", "a"]
if array1.sorted() == array2.sorted() {
print("array 1 & array 2 are same")
}
Run Code Online (Sandbox Code Playgroud)
你可以这样做:
array1.sortInPlace()
array2.sortInPlace()
print(array1,array2)
if array1 == array2 {
print("equal")
} else {
print("not equal")
}
Run Code Online (Sandbox Code Playgroud)
如果不想改变原始阵列,我们可以做到
let sorted1 = array1.sort()
let sorted2 = array2.sort()
if sorted1 == sorted2 {
print("equal")
}else {
print("not equal")
}
Run Code Online (Sandbox Code Playgroud)
使用 Set
let array1 = ["a", "b", "c"]
let array2 = ["b", "c", "a", "c"]
let set1 = Set(array1)
let set2 = Set(array2)
if (set1.count == set2.count && set1 == set2) { //if you compare big sets it is recommended to compare the count of items in the sets beforehand
//they are identical
}
Run Code Online (Sandbox Code Playgroud)
该Set工具Hashable做任务是贯彻落实哈希函数与工作Set