2

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'
0

1 Answer 1

4

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
Sign up to request clarification or add additional context in comments.

3 Comments

thank you, could you please help me with the updated question as well?
god I'm a noob, now I can't get the cell.textLabel?.text = cellitemcontent(indexPath.row) to work...
cellitemcontent[indexPath.row][0] as String

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.