如何让arc4random在swift

时间:2016-04-06 12:05:06

标签: ios swift

当我在文本字段中写下5个名字时,如何让arc4random选择4个不同的名字而不回复?

 import UIKit

class ViewController: UIViewController, UIPickerViewDelegate {

    var array = [String]()

    @IBOutlet var textfi1: UITextField!
    @IBOutlet var textfi2: UITextField!
    @IBOutlet var textfi3: UITextField!
    @IBOutlet var textfi4: UITextField!
    @IBOutlet var textfi5: UITextField!


    @IBOutlet weak var lbl: UILabel!



    override func viewDidLoad() {
        super.viewDidLoad()


    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    @IBAction func button(sender: AnyObject) {

          numberFive()

    }

    func numberFive() {

        array = [ textfi1.text! ,  textfi2.text! , textfi3.text! , textfi4.text! , textfi5.text! ]

        let randomIndex = Int(arc4random_uniform(UInt32(5)))

        lbl.text! = "\(array[randomIndex]) with \(array[randomIndex]) \n  \(array[randomIndex]) with \(array[randomIndex])"

        lbl.numberOfLines = 0

        }    

    }

1 个答案:

答案 0 :(得分:0)

正如我所理解的那样,你想从5个名字的列表中随机选择4和(随机)将它们分成两对。

/* say these are the names from the .text property
   of your UITextField instances */
var names = ["David", "Lisa", "Greg", "Hannah", "Richard"]

/* create an array of tuples to hold the pairs */
var pairs : [(String, String)] = []

/* randomly assign 4 out of 5 names into two pair containers */
let numPairs = names.count/2 // Int division => rounds down by simply dropping decimal value
for _ in 0..<numPairs {
    var newPair : (String, String)
    newPair.0 = names.removeAtIndex(Int(arc4random_uniform(UInt32(names.count))))
    newPair.1 = names.removeAtIndex(Int(arc4random_uniform(UInt32(names.count))))
    pairs.append(newPair)
}

/* random result */
pairs.forEach { print("\($0.0) with \($0.1)") }
/* Hannah with Lisa
   Greg with Richard */

应用于您的示例:

// ... in your ViewController class

func divideIntoPairs() {

    if let name1 = textfi1.text, name2 = textfi2.text,
        name3 = textfi3.text, name4 = textfi4.text,
        name5 = textfi5.text {

        var names = [name1, name2, name3, name4, name5]

        var pairs : [(String, String)] = []

        let numPairs = names.count/2
        for _ in 0..<numPairs {
            var newPair : (String, String)
            newPair.0 = names.removeAtIndex(Int(arc4random_uniform(UInt32(names.count))))
            newPair.1 = names.removeAtIndex(Int(arc4random_uniform(UInt32(names.count))))
            pairs.append(newPair)

        }
        pairs.forEach { print("\($0.0) with \($0.1)") }
        /* 'SomeName' with 'AnotherName'
           'EvenAnotherName' with 'AFinalOtherName' */ 

        // or, to set this as a single String to UILabel: text property
        lbl.text = pairs.map { "\($0.0) with \($0.1)" }.joinWithSeparator("\n")
    }
}