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

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.

Related

Array that looks like dictionary?

So I have a plist with a number of items that I would like to access in my project. The plist is an array of items, which are in turn dictionaries with of type string:string (Item1 -> "name" : "somename", "description" : "somedescription")
I would like to access only the name value of my items, and display in an array. I have managed to retreive all the key-value pairs in my plist with the following code:
let path = Bundle.main.path(forResource: "PlistName", ofType: "plist")
let dict = NSArray.init(contentsOf: URL.init(fileURLWithPath: path!)) as! [[String:String]]
by using print(dict) I am able to get everything printed to the console, however like I said I only want the names of the items in an array.
What confuses me the most is the fact that the dict is equal to an NSArray of type [[String:String]]. I do not understand how an array can be of type String:String. This looks like a dictionary to me. I tried changing NSArray to NSDictionary, but that gives me an error saying
"Cast from 'NSDictionary?' to unrelated type '[[String : String]]' always fails"
I'm also not able to tap into either the key or value of dict.
let oneDict = dict[0]
returns one dictionary, and if you really want an array of one dictionary do this:
let array = [oneDict]
You can extract values for a specific key by using the map or compactMap functions, in this case I use compactMap in case one of the dictionaries doesn't contain a name
let arrayOfDictionaries = [["name": "a", "some": "x"],
["name": "b", "some": "y"],
["some": "z"],
["name": "c"]]
let names = arrayOfDictionaries.compactMap {$0["name"]}

How to freeze an array in swift?

In js I can freeze an array after adding some elements to an array.
Is there anything to freeze an array in Swift?
What is freezing?
Ans: Suppose we have an array. We add some elements
to that array.
/* This is javascript code */
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Kiwi");
// fruits contains some elements
// Now freeze fruits. After freezing, no one can add, delete, modify this array.
Object.freeze(fruits);
My question is here - "Is there anything in swift where we can freeze an array?"
You can create an immutable copy of the array, but the mutability of objects is only controlled by the variable declaration (let for immutable and var for mutable), so once you create a mutable object, you cannot make it immutable or vice-versa.
var fruits = ["Banana", "Orange", "Apple", "Mango"]
fruits.append("Kiwi")
let finalFruits = fruits // Immutable copy
finalFruits.append("Pear") // Gives compile-time error: Cannot use mutating member on immutable value: 'finalFruits' is a 'let' constant

How to access individual elements in an array if the array is stored as a value in a Dictionary

I'm new to coding and this is my first post!
I have created a dictionary in Swift where each individual value is an array.
Ex
1: [0.0443, 0.220832, 0.526799, 0.72147, 0.646954,0.511456,1.00405]
What I need to do is to access the value and store into a different array for data manipulation.
I am having trouble doing this because swift is viewing the array as a single object.
ex. dict[1]!.count will print 1 not 7 (ie. the 7 values)
Is there a way to do this - meaning to get swift to store the value as an array of Doubles?
Thanks.
It would be nice if you shared some code with us. but to access a dictionary of arrays you can do something like this :
let array1 = ["a", "b" , "c"]
let array2 : [Float] = [1.2,2.8,3.4]
let dictionary : Dictionary<String, Any> = ["array1" : array1, "array2" :array2]
var arrayFromDictionary = dictionary["array1"] as! [String]
var array2FromDictionary = dictionary["array2"] as! [Float]
print(arrayFromDictionary[1])
print(array2FromDictionary[2])
the first print call will print out "b" since it is the second member of the array1.
the second print call will print out 3.4 since it is the third member of array2.
does this answer your question ?

Swift 2: Writing to plist with multidimensional objects

I am a newbie in Swift and I have been trying something for a long time and I am having an compile error that could not overcome with.
I am trying to write to a plist containing multidimensional array objects.
I need to add an array to the inner array of plist.
The plist is like as follows:
I am trying to populate the most inner array of the plist which is as follows:
I am trying to add ITEM 2 under the ITEM 5.
I am using this code:
notesArray.objectAtIndex(0).objectAtIndex(5).addObject("AA","BB","CC","DD")
Compiler gives me following error :
Cannot call value of non-function type '((AnyObject) -> Void)!'
How can I populate the array inside the parent array directly from the code?
Due to value semantics of Swift arrays you have to reassign all changes to their parent objects
This is the initial array
var array : [AnyObject] = [["OZEN PIZZA", "PIZZA", "15", "20", "tariffoto1", [["Biber","2", "Adet", "11"]]]]
get the root array at index 0 of the array
var rootArray = array[0] as! [AnyObject]
get the array at index 5 of rootArray
var item5Array = rootArray[5] as! [[String]]
append the item
item5Array.append(["AA","BB","CC","DD"])
reassign item5Array to index 5 of rootArray
rootArray[5] = item5Array
reassign rootArray to index 0 of the array
array[0] = rootArray

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

Resources