作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
当我在文本字段中写入 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/
我是一名优秀的程序员,十分优秀!