我有两个相同大小的数组,我排序第二个。如何排列第一个匹配?
基本示例(假设用Ints
替换Strings
):
var array1 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
var array2 = [5, 2, 3, 4, 5, 6, 8, 5, 4, 5, 1]
array2.sort = ({ $0 > $1})
结果:
array2 is now [8, 6, 5, 5, 5, 5, 4, 4, 3, 2, 1]
如何对array1的索引值进行排序以匹配array2?
array1 should now be [6, 5, 0, 4, 7, 9, 3, 8, 2, 1, 0]
答案 0 :(得分:4)
Zip2
,sorted
和map
array1 = map(sorted(Zip2(array1, array2), {$0.1 > $1.1}), { $0.0 })
合并filter
var array1 = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0"]
var array2 = [5, 2, 3, 4, 5, 6, 8, 5, 4, 5, 1]
func isEven(x:Int) -> Bool {
return x % 2 == 0
}
let result = map(sorted(filter(Zip2(array1, array2), { isEven($0.1) }), {$0.1 > $1.1}), { $0.0 })
// -> ["6", "5", "3", "8", "1"]
如您所见,该行过于复杂,您可能需要Array
方法链语法:
let result2 = Array(Zip2(array1, array2))
.filter({ isEven($0.1) })
.sorted({ $0.1 > $1.1 })
.map({ $0.0 })
无论如何,如果您的array2
是[PFObject]
,您可以实现以下功能:
func isOpen(restaurant: PFObject, forTime time: String, onDay day: Int) -> Bool {
// return `true` if the restaurant is open, `false` otherwise
}