JoeShmoe JoeShmoe - 6 months ago 7
Swift Question

Unable to combine multiple arrays

I'm trying to combine these two arrays (x and y). These would combine for form array A, But I am getting multiple build errors. First I am getting a "Consecutive declarations on a line must be separated by ';'" error as well as an expected declaration error. I am not sure how to proceed as this is the first time I've attempted this in Swift. Any guidance would be helpful.

var x = [
"Nation Flags",
"Landmarks",
"Smash",
"History",
"Famous People",
"Word Find",
"Quiz",
"Test Your Knowledge"]

var y: [AnyObject] = [Int(true), Int(false), Int(true), Int(false), Int(false),Int(false),Int(false),Int(false),]

var challengesArray: [AnyObject] = [AnyObject]()

for (index, value) in x.enumerate() { // <-- here is the new loop
var Challenge: [NSObject : AnyObject] = [
"challenge" : x[index],
"status" : y[index]
]

challengesArray.append(Challenge)
}

Answer

here is the recommanded way to loop, it will probably not fix your error, but could help:

you have to wrap the code in a method/function you cannot execute for loop in a class declaration.

class GameSelectorViewController: UIViewController, UITableViewDataSource,   UITableViewDelegate {

var x = [
    "xxxxx xxxxx",
    "xxxxxxxx xxxxxxxx",
    "xxxxxx xxxxxxx",
    "xxxxxxxx xxxxxxxx"]

var y: [AnyObject] = [Int(true), Int(false), Int(true), Int(false)]

var A: [AnyObject] = [AnyObject]()

func combineArray() { // <-- here is the function
    for (index, value) in x.enumerate() { // <-- here is the new loop
        var Challenge: [NSObject : AnyObject] = [
            "challenge" : x[index],
            "status" : y[index]
        ]

        A.append(Challenge)
    }
}

    override func viewDidLoad() {

        super.viewDidLoad()
        self.combineArray()
        // Do any additional setup after loading the view.
    }
}
Comments