How do I shuffle an array in Swift?

前端 未结 25 2645
长发绾君心
长发绾君心 2020-11-21 05:44

How do I randomize or shuffle the elements within an array in Swift? For example, if my array consists of 52 playing cards, I want to shuffle the array in o

25条回答
  •  轮回少年
    2020-11-21 06:21

    It stop at "swap(&self[i], &self[j])" when I upgrade the xCode version to 7.4 beta.
    fatal error: swapping a location with itself is not supported

    I found the reason that i = j (function of swap will exploded)

    So I add a condition as below

    if (i != j){
        swap(&list[i], &list[j])
    }
    

    YA! It's OK for me.

提交回复
热议问题