# swift扩展数组shuffle函数，随机排序数组

**URL:** https://www.shiqidu.com/t/topic/220
**Category:** 开发调优
**Tags:** Swift
**Created:** [2017 年9 月 5 日 03:20 UTC](https://www.shiqidu.com/t/topic/220 "2017-09-05T03:20:23Z")
**Posts on this page:** 2
**Page:** 1

<div class="post-metadata">

### 作者： ![Eureka](https://www.shiqidu.com/user_avatar/www.shiqidu.com/eureka/32/5_2.png) [@Eureka](https://www.shiqidu.com/u/Eureka)
#### 发布日期： [2017 年9 月 5 日 03:20 UTC](https://www.shiqidu.com/t/topic/220/1 "2017-09-05T03:20:23Z")

</div>

大家都知道`php`有`shuffle`函数可以很方便的随机排序一个数组，下面分享一个`swift`的`shuffle`函数，用于随机排序一个数组。

```swift
extension Array{
    public func shuffle() -> Array {
        var list = self
        for index in 0..<list.count {
            let newIndex = Int(arc4random_uniform(UInt32(list.count-index))) + index
            if index != newIndex {
                swap(&list[index], &list[newIndex])
            }
        }
        return list
    }
}

// 生成一个数组
var arr = Array<Int>();
arr.append(contentsOf: 1...10)
arr.shuffle()
// 输出结果如下
// [10, 6, 3, 5, 4, 2, 8, 1, 9, 7]

```

### 另一种方法排序数组的方法

```swift
let arrShuffle = arr.sorted() {(_,_) -> Bool in
    arc4random() < arc4random()
}
print(arrShuffle)
// 输出如下
// [6, 2, 3, 5, 4, 1, 7, 8, 9, 10]

```

这种是最简单的方法，利用一个闭包函数排序数组。但是这种方法无论效率还是可拓展性上都不如第一种方法。

---

<div class="post-metadata">

### 作者： ![caojie](https://www.shiqidu.com/user_avatar/www.shiqidu.com/caojie/32/465_2.png) [@caojie](https://www.shiqidu.com/u/caojie)
#### 发布日期： [2017 年9 月 8 日 06:52 UTC](https://www.shiqidu.com/t/topic/220/2 "2017-09-08T06:52:09Z")

</div>

加油
