二维空数组(字符串和Bool)

时间:2021-04-28 21:35:24

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.

我有一个待办事项列表,在单元格中有一个复选框。目前,我将todo项存储在一个数组中,bool值存储在另一个数组中……我的应用程序开始变大了,所以我想把它们都放在一个数组中。

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:

如何存储2D数组?当它是1D时,我会这样储存:

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

1 个解决方案

#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:

如果您需要使用用户默认值来存储它,您可以使用子数组而不是tuple,如下所示:

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

#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:

如果您需要使用用户默认值来存储它,您可以使用子数组而不是tuple,如下所示:

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