14
14

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

SwiftのExtensionを使って、ArrayとNSMutableArrayのランダムソートメソッドを作ってみた

Posted at

Extension専用のファイルを適当に作ります。
そして、その中にメソッドを作ります。

Extension.swift
//
//  Extension.swift
//  TinderStyleApp
//
//  Created by kiiita on 2014/09/06.
//  Copyright (c) 2014年 kiiita. All rights reserved.
//

import Foundation

extension Array {
    mutating func shuffle(count: Int) {
        for _ in 0..<count {
            sort { (_,_) in arc4random() < arc4random() }
        }
    }
}

extension NSMutableArray {
    func shuffle(count: Int) {
        for i in 0..<count {
            var nElements: Int = count - i
            var n: Int = Int(arc4random_uniform(UInt32(nElements))) + i
            self.exchangeObjectAtIndex(i, withObjectAtIndex: n)
        }
    }

}

あとは使いたい部分で呼び出すだけです。
正しく動いていれば、補完で出てきます。

VC.swift
var exampleArray: NSMutableArray = NSMutableArray()

override func viewDidLoad() {
	super.viewDidLoad()

	exampleArray = ["hoge", "huga", "piyo"]
	exampleArray.shuffle(exampleArray.count)
	
}
14
14
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
14

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?