arraysswift2ddimensional

2D empty array ( String and Bool) in swift


I see some questions for multidimensional arrays and two dimensional arrays but none of them show how to correctly implement an empty array.

I have a todo list where I have a checkbox in the cell. Currently I'm storing the todo item in an array and the bool value in another array...My app is starting to get big so I'd prefer to have them both in one array.

How do I correctly do it?

var cellitemcontent = [String:Bool]() 

if this is the correct way then I get errors at

cellitemcontent.append(item) //String: Bool does not have a member named append

So I'm assuming this is how to declare a Dictionary not a 2D array...

Also how would I store a 2D array? When it's 1D I store it like this:

NSUserDefaults.standardUserDefaults().setObject(cellitemcontent, forKey: "cellitemcontent") // Type '[(name: String, checked: Bool)]' does not conform to protocol 'AnyObject'

Solution

  • You can create an array of tuples as follow:

    var cellitemcontent:[(name:String,checked:Bool)] = []
    
    cellitemcontent.append(name: "Anything",checked: true)
    
    cellitemcontent[0].name    // Anything
    cellitemcontent[0].checked // true
    

    If you need to store it using user defaults you can use a subarray instead of a tuple as follow:

    var cellitemcontent:[[AnyObject]] = []
    
    cellitemcontent.append(["Anything", true])
    
    cellitemcontent[0][0] as String   // Anything
    cellitemcontent[0][1] as Bool     // true
    
    NSUserDefaults().setObject(cellitemcontent, forKey: "myArray")
    let myLoadedArray = NSUserDefaults().arrayForKey("myArray") as? [[AnyObject]] ?? []
    
    myLoadedArray[0][0] as String
    myLoadedArray[0][1] as Bool