2D empty array ( String and Bool) in swift - arrays

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'

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

Related

Access items from an Array that is inside a Dictionary in Swift

I have a Dictionary which contains an array of fruits and a Double. What I would like to be able to do is access the fruits inside the array.
How can I access items inside the fruits array?
var fruits = ["Apple", "Oranges"]
var fruitDictionary:[String: Any] = ["fruits":fruits, "car":2.5]
print("Dictionary: \(fruitDictionary["fruits"]!)") // output: Dictionary: ["Apple", "Oranges"]
I tried...
print("Dictionary: \(fruitDictionary["fruits"[0]]!)")
and...
print("Dictionary: \(fruitDictionary["fruits[0]"]!)")
But no luck
Thanks
First you need to access the fruits entry of the dictionary and cast it as an array of strings.
From there you can access the elements of the array.
if let array = fruitDictionary["fruits"] as? [String] {
print(array[0])
}
The reason why your attempts did not work is because the values in your dictionary are of type Any, which might not be able to be accessed through a subscript.

Extract an array from a collection [duplicate]

This question already has answers here:
Get an array of property values from an object array
(2 answers)
Closed 6 years ago.
I get an element from a collection with this code:
modelCollec[indexPath].model
I want to get all models in an array. Is there a function or shall I write a loop?
There is only one row so indexPath is always [0, index].
Use flatMap for that.
let modelArray = modelCollec.flatMap { $0.model }
modelArray type is [model].
For eg:
struct Person {
var name: String
}
Now if you have array of person and you want array of name from it you can get it using flatMap like this way.
let persons = [Person]()
let nameArray = persons.flatMap { $0.name } //nameArray type is [String]
Note: You can also use map instead of flatMap but it will give you optional objects if your model property is optional so it may contains nil where as flatMap ignore the nil object.
If you always want to access the 1st element of the collection then it is a better idea to hardcode the 0 index rather than using loop, however to it is always better to put a check for nil.

Swift: Filter array of array of Object

I have the following structure
aSectionArray = [[objA, objB, objC], [obj1, obj2, obj3], [objX, objY, objZ]]
objA is having a bool, say isEnabled.
I need to filter the aSectionArray based this bool (say isEnabled == true).
Help needed.
You could use flatten() and filter, like this (Swift 2):
let result = aSectionArray.flatten().filter { $0.isEnabled }
it will give you the objects where isEnabled is true.
We use flatten() to make the 2D array into a 1D array, and we use filter to get the objects where the closure verifies.
In Swift 3 (Xcode 8 beta 6) flatten has become joined:
let result = aSectionArray.joined().filter { $0.isEnabled }

addObjectsFromArray to the beginning of an existing array

I'm having trouble adding an existing array to the beginning of another array.
For example:
MutableID array contains 1,2,3,4,5 & idArray array contains 6,7,8
self.MutableID.addObjectsFromArray(idArray as [AnyObject])
//currently puts values to the end of the array not the beginning
this code outputs 1,2,3,4,5,6,7,8 but I want it to output 6,7,8,1,2,3,4,5
I need the values added to the beginning of self.MutableID Any suggestions on how I can accomplish this?
NSMutableArray has insertObjects method.
self.MutableID.insertObjects(otherArray as [AnyObject], atIndexes: NSIndexSet(indexesInRange: NSMakeRange(0, otherArray.count)))
Or you can assign the mutable array to a swift array and use insertContentsOf method ;)
self.MutableID = NSMutableArray(array: [1,2,3,4])
var otherArray = NSMutableArray(array: [6,7,8,9])
var swiftArr : [AnyObject] = self.MutableID as [AnyObject]
swiftArr.insertContentsOf(otherArray as [AnyObject], at: 0)
self.MutableID.insertContentsOf(idArray as [AnyObject], at: 0)
This question is the Swift version of this question which solves the problem in Objective-C.
If we must, for whatever reason, be using Objective-C's NSArray or NSMutableArray, then we can simply use a Swift translation of the code in my answer over there:
let range = NSMakeRange(0, newArray.count)
let indexes = NSIndexSet(indexesInRange: range)
oldArray.insertObjects(newArray as [AnyObject], atIndexes: indexes)
Where oldArray is an NSMutableArray and newArray is NSArray or NSMutableArray.
Or the other approach, append and reassign:
oldArray = newArray.arrayByAddingObjectsFromArray(oldArray as [AnyObject])
But the most correct thing to do would be to use the Swift Array type, and then use the insertContentsOf(_: Array, at: Int) method, as fluidsonic's answer describes.

Is it possible to append a new object to a heterogenous array in swift?

I know that true mutability can not be achieved in swift. I have an array interspersed with different types of contents.
let myArray = String[]();
var array = ["First","Second","Third",1,0.4,myArray,"dsaa"]
I learned from the above post I have linked that we will be able to append items to an array. But each time I add a new item to the array I have declared above I get this error:
could not find an overload for '+=' that accepts the supplied
arguments
But when the array is homogeneous, I am able to add an item which is same as the already present items, without hassle. but still the item with a different type can not be added.
If you declare your second array explicitly as AnyObject[], you can do it:
let myArray = String[]()
var array:AnyObject[] = ["First", "Second", "Third", 1, 0.4, myArray, "dsaa"]
let n1 = array.count // 7
array += "next"
let n2 = array.count // 8

Resources