【问题标题】:Swift mastermind迅捷的策划者
【发布时间】:2015-07-26 08:38:54
【问题描述】:

我尝试快速创建一个 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) {

    }
}

我需要帮助

【问题讨论】:

  • 您在代码中尝试了什么?这没有多大意义。
  • 看来他正试图单独获取4位随机数的每个数字。
  • 改变了答案,这应该得到你想要的
  • 请清楚您所说的“无效”是什么意思。您希望发生什么?究竟发生了什么?

标签: swift


【解决方案1】:

如果您尝试单独获取随机数的每个数字:

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

编辑:简化的事情

【讨论】:

  • 我不完全确定你想要什么,但你应该能够通过这个例子得到你需要的东西
  • 你能解释一下你做了什么吗?
  • 首先,你生成一个随机数,将这个数转换为String并存储在code中。 map()code 转换为 String 类型的数组并将其存储在 separated 中。现在你有了一个数组,可以尝试使用contains() 来检查数组是否包含find
  • 现在它将遍历“数字”数组并检查文本字段的“数字”是否与其中任何一个匹配。
【解决方案2】:

把随机数变成字符数组,

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
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-08
    • 1970-01-01
    相关资源
    最近更新 更多