gpt4 book ai didi

ios - 如何让 arc4random 在 swift 中选择 4 个不同的名称

转载 作者:行者123 更新时间:2023-11-30 13:32:09 27 4
gpt4 key购买 nike

当我在文本字段中写入 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

}

}

最佳答案

据我了解,您希望从 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")
}
}

关于ios - 如何让 arc4random 在 swift 中选择 4 个不同的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36450613/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com