如何连接两个不同的阵列并同时将它们随机化?

时间:2019-02-22 13:27:03

标签: arrays swift xcode

我试图连接2个阵列,但同时将它们随机化,例如:

数组1:A,B,C,D,E 数组2:1、2、3、4、5

当我按下显示按钮时,我希望字母与数字相对应,但我希望它们随机出现

C / 3,A / 1,E / 5

现在我的源代码将我的数组随机化,但是它们没有顺序,这意味着我得到的是A / 2,E / 1,C,5。这是我的代码:

 @IBOutlet weak var randomLetter: UIButton!
 @IBOutlet weak var randomNumber: UIButton!

 @IBAction func showLetters(_ sender: Any) {

    let array1 = ["A","B","C","D","E"]


    let array2 = ["1","2","3","4","5"]


      let randomLetterGen = Int (arc4random_uniform(UInt32(array2.count)))
    randomLetter.text = array2 [randomLetterGen]

      let randomNumberGen = Int (arc4random_uniform(UInt32(array1.count)))
    randomNumber.text = array1 [randomNumberGen]

}

2 个答案:

答案 0 :(得分:0)

此代码有效

var array1 = ["A","B","C","D","E"]
    let array2 = ["1","2","3","4","5"]
    array2.forEach { (item) in
        array1.append(item)
    }
    print(array1.shuffle())

答案 1 :(得分:0)

您可以通过对array1array2使用相同的随机索引来实现这一目标。

考虑以下代码:

let array1 = ["A","B","C","D","E"]
let array2 = ["1","2","3","4","5"]

let randomLetterGen = Int(arc4random_uniform(UInt32(array2.count)))
randomLetter.text = array2[randomLetterGen] //C
randomNumber.text = array1[randomLetterGen] //3