尝试将字符串与数组中的元素进行比较时出错

时间:2014-11-13 01:49:09

标签: xcode swift

    let verbList: [String] = ["hacer", "ser", "estar"]
let POVList: [String] = ["él / usted","ella / usted","ellas / ustedes","ellos / ustedes","tú","yo","nosotros",]
let correctConjugation: [[String]] = [["hace","hace","hacen","hacen","haces","hago","hacemos"], ["es","es","son","son","eres","soy","somos"], ["está","está","estan","estan","estas","estoy","estamos"]]


func randomVerb() -> Int {                          //creates and returns a random number for the prefix arrray
    var randomVerb = Int(arc4random_uniform(3))
    return randomVerb
}

func randomPrefix() -> Int {                        //creates and returns a random number for the verb array
    var randomPrefix = Int(arc4random_uniform(7))
    return randomPrefix
}


@IBAction func changeVerb(sender: AnyObject) {

    Verb.text = verbList[randomVerb()]
    POV.text = POVList[randomPrefix()]

    userResponse.backgroundColor = UIColor.whiteColor()
    userResponse.text = ""


}


@IBAction func checkResponse(sender: AnyObject) {

    var userResponseA: String
    userResponseA = userResponse.text
    if (userResponseA == correctConjugation[randomVerb()[randomPrefix()]]){
        userResponse.backgroundColor = UIColor.greenColor()
    } else {
        userResponse.backgroundColor = UIColor.redColor()
    }

}

所以我在这里得到两个错误(在checkResponse的if语句中):首先," int没有一个名为' subscript'"如果我只是在if语句中取出对函数的调用,我得到:"' String'不能转换为镜像配置'"

我真的不知道为什么这不起作用。忍受我,因为我是一个Xcode noob,只是想用西班牙语获得更好的成绩。

1 个答案:

答案 0 :(得分:1)

非常接近 - 只需将您的下标分开:

if (userResponseA == correctConjugation[randomVerb()][randomPrefix()]) {
    // ...
}

使用数组数组(在本例中为correctConjugation)时,每个下标都会向下移动一级。


对于另一个问题,您需要一些变量来保存当前的动词和前缀索引:

class VC: UIViewController {
    // list declarations here
    var verbIndex = 0
    var povIndex = 0

    @IBAction func changeVerb(sender: AnyObject) {
        verbIndex = randomVerb()
        povIndex = randomPrefix()

        Verb.text = verbList[verbIndex]
        POV.text = POVList[povIndex]

        userResponse.backgroundColor = UIColor.whiteColor()
        userResponse.text = ""
    }

    @IBAction func checkResponse(sender: AnyObject) {
        var userResponseA = userResponse.text

        if (userResponseA == correctConjugation[verbIndex][povIndex]){
            userResponse.backgroundColor = UIColor.greenColor()
        } else {
            userResponse.backgroundColor = UIColor.redColor()
        }
    }
}