Search code examples
swiftxcode9

how can i solve this "Cannot subscript a value of type `[[String]]` with an index of type `UInt32`"


i'm having a problem about this UInt32 thing, the "answer" in my button is having an error about this "Cannot subscript a value of type [[String]] with an index of type UInt32"

let answers = [["1. After the exam, I felt too exhausted and famished to eat my foods.","2. I could eat a horse, I am a famish now.","3. I famished my stomach next time you treat me to a meal out.","4. I will bring lots of pizza, that's famish."],["Would","Has to","Must","Could"]]  

var rightanswerplacement:UInt32 = 0


 rightanswerplacement = arc4random_uniform(2)+1
        var button:UIButton = UIButton()

        var x = 1

        for i in 1...3{

                button = view.viewWithTag(i) as! UIButton

            if (i == Int(rightanswerplacement)){
                button.setTitle(answers[rightanswerplacement][0], for: UIControlState.normal)

            }
            else{
                button.setTitle(answers[rightanswerplacement][x], for: UIControlState.normal)
                x = 2
            }

            currentquestions += 1

        }

Solution

  • Use Int for subscripts.

    Note: I removed the views to test the correctness of Int.

    let answers = [["1. After the exam, I felt too exhausted and famished to eat my foods.","2. I could eat a horse, I am a famish now.","3. I famished my stomach next time you treat me to a meal out.","4. I will bring lots of pizza, that's famish."],["Would","Has to","Must","Could"]]
    
    var rightanswerplacement: Int = 0
    rightanswerplacement = Int(arc4random_uniform(2)) + 1
    var x = 1
    for i in 1...3 {
        if (i == Int(rightanswerplacement)) {
            print(answers[rightanswerplacement][0])
        } else {
            print(answers[rightanswerplacement][x])
            x = 2
        }
    }
    

    Output

    Would
    Has to
    Must