我尝试在swift中创建一个Mastermind但是我无法使用索引来获取随机数的每个数字来检查我是否找到了一些代码。 我试过这个,但它不起作用..:
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var textField: UITextField!
@IBOutlet weak var textView: UITextView!
var code = String(arc4random_uniform(9000) + 1000)
override func viewDidLoad() {
super.viewDidLoad()
println(code)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
self.view.endEditing(true)
}
@IBAction func sendDidPressed(sender: AnyObject) {
var find = 0
for (var i = 0; i < 4; i++) {
var number = textField.text
var numberInCode = map(code) { String($0) }
if contains(numberInCode, String(find)) {
find++
}
self.textView.text = "\(self.textField.text): Bien placées: \(String(find))"
}
}
@IBAction func resetCode(sender: AnyObject) {
}
}
我需要帮助
答案 0 :(得分:0)
如果您试图单独获取随机数的每个数字:
class ViewController: UIViewController {
var code = [String]()
let textFromField = "1" // Text from your textField
override func viewDidLoad() {
let number = String(arc4random_uniform(9000) + 1000)
code = map(number) { String($0) }
}
@IBAction func sendDidPressed(sender: AnyObject) {
for index in 0..<code.count {
if textFromField == code[index] {
println("Match found at index: \(index + 1)")
}
}
}
}
code
现在是Array
,其数字分隔为Strings
您应该更改将随机数转换为Int的方式,因为根据此post:
Int(arc4random())
将在32位平台上执行50%的时间,因为UInt32不适合Int32
编辑:简化的事情
答案 1 :(得分:0)
将随机数转换为字符数组
var code = (arc4random_uniform() % 9000 + 1000) //e.g. 1245
var codeAsArray = Array(String(code)) //e.g. [1, 2, 4, 5]
for (var i = 0; i < 4; i++) {
// var number = textField.text
println(codeAsArray[i]) //is a swift Character
}