Help us understand the problem. What is going on with this article?

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

More than 5 years have passed since last update.

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)

}
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした