使用shuffle()
方法来自如何在 Swift 中打乱数组?以及来自的想法如何根据另一个数组的排序顺序对多个数组进行排序你可以打乱数组indices然后重新订购两个(或多个)
相应的数组:
let a = [1, 2, 3, 4]
let b = ["a", "b", "c", "d"]
var shuffled_indices = a.indices.shuffle()
let shuffled_a = Array(PermutationGenerator(elements: a, indices: shuffled_indices))
let shuffled_b = Array(PermutationGenerator(elements: b, indices: shuffled_indices))
print(shuffled_a) // [3, 1, 2, 4]
print(shuffled_b) // ["c", "a", "b", "d"]
Swift 3 (Xcode 8) 更新: PermutationGenerator
才不是
Swift 3 中不再存在。
使用shuffled()
方法
从随机排列数组 swift 3同样可以通过以下方式实现
var shuffled_indices = a.indices.shuffled()
let shuffled_a = shuffled_indices.map { a[$0] }
let shuffled_b = shuffled_indices.map { b[$0] }