Randomize two arrays the same way Swift

后端 未结 4 2210
我寻月下人不归
我寻月下人不归 2021-01-21 04:36

I know there is a new shuffle method with iOS 9 but I am wondering if there is anyway to shuffle two arrays the same way?

For example

[1         


        
4条回答
  •  天涯浪人
    2021-01-21 04:36

    Based upon Martin R's original answer, you could approach the problem using GameKit.

    The answer is written in Swift4:

    var arrayA = [1, 2, 3, 4]
    var arrayB = ["a", "b", "c", "d"]
    
    //Get The Indices Of The 1st Array 
    var shuffledIndices: [Int] = Array(arrayA.indices)
    print("Shuffled Indices = \(shuffledIndices)")
    
    //Shuffle These Using GameKit
    shuffledIndices = GKRandomSource.sharedRandom().arrayByShufflingObjects(in: shuffledIndices) as! [Int]
    
    //Map The Objects To The Shuffled Indices
    arrayA = shuffledIndices.map { arrayA[$0] }
    arrayB = shuffledIndices.map { arrayB[$0] }
    
    //Log The Results
    print("""
    Array A = \(arrayA)
    Array B = \(arrayB)
    """)
    

    Hope it helps ^_________^.

提交回复
热议问题