Add new key value to all the elements in array of dictionary - swift

I have a array of dictionary.
I need to add a new key and a value to all the elements of array of dictionary.
Please guide.

You need to extract the dictionary from the array, modify it and put back to the array, since arrays and dictionaries in Swift are value types.
Something like this should work for you:
var arrayofDict = [["1": 1], ["2": 2], ["3": 3]]
for i in 0..<arrayofDict.count {
var dict = arrayofDict[i]
dict["random"] = Int(arc4random_uniform(8)) //random integer value
arrayofDict[i] = dict
}
print(arrayofDict) //prints "[["1": 1, "random": 2], ["2": 2, "random": 0], ["random": 2, "3": 3]]\n"

Related

Array with multiple values per index?

I'm learning swift, and I do the sololearn course to get some knowledge, but I bumped into something that I don't understand.
It is about modifying an array's values. The questionable part states the following:
In the following example, the elements with index 1, 2, 3 are replaced with two new values.
shoppingList[1...3] = [“Bananas”, “Oranges”]
How can an one dimensional array take more than one value per index? And how do I access them? Am I misunderstanding something?
What this code does is replacing the element of shoppingList in the 1...3 range using Array.subscript(_:)
That means considering this array:
var shoppingList = ["Apples", "Strawberries", "Pears", "Pineaples"]
that with:
shoppingList[1...3] = ["Bananas", "Oranges"]
Strawberries, Pears and Pineaples will be replaced by Bananas and Oranges.
so the resulting array will be: Apples, Bananas, Oranges
When you assign to a range of indices in an array (array[1...3]), those elements are removed from the array and the new elements are 'slotted in' in their place. This can result in the array growing or shrinking.
var array = Array(0...5)
// [0, 1, 2, 3, 4, 5]
array[1...3] = [-1, -2]
// [0, -1, -2, 3, 4]
Notice how our array's length is now one element shorter.
You could use a tuple (Value, Value), or create a struct to handle your values there, in fact if you plan to reuse this pair or value, a struct is the way to go.
By the way, there's no need to add [1..3], just put the values inside the brackets.
struct Value {
var name: String
var lastName: String
}
let values = [Value(name: "Mary", lastName: "Queen"), Value(name: "John", lastName: "Black")]
// Access to properties
let lastName = values[1].lastName
// OR
let tuples = [("Mary", "Queen"), ("John", "Black")]
let lastNameTuple = tuples[1].1
Hope you're enjoying Swift!

How to replace slice of array in Swift?

To replace a slice of array in Swift, we can use subscript assignment or replaceSubrange method on array. But, I wonder how can I change the elements of named subrange so that original array change as well?
var array = Array(0..<10)
var slice = array[0..<3]
slice[...] = [-1,-1,-1]
print(slice) // [-1, -1, -1]
print(array) // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] does not change

Reduce to count elements in a dictionary in Swift

I'm trying to count the elements of my dictionary. The dictionary is of type [EKCalendar: ReminderList] where ReminderList is a class with a list property. I want to go through the dictionary and add up the count of all these lists.
My dictionary is in the property self?.reminderListsStructure.structure.
let numberOfElements = self?.reminderListsStructure.structure.reduce(0) {
accumulator, nextValue in
return accumulator.list.count + nextValue.list.count
// COMPILE ERROR: Type of expression is ambiguous without more context
}
let count = reminderListsStructure.structure.reduce(0) { $0 + $1.1.list.count }
Something like this. Not enough info though, so I'm not 100% sure it works.
I think flatMap is a more appropriate choice here:
let input = [
1: [1],
2: [1, 2],
3: [1, 2, 3],
4: [1, 2, 3, 4],
5: [1, 2, 3, 4, 5]
]
let output = input.values.flatMap{$0}.count //15
When you reduce a dictionary, the element type is a tuple of the Key and Value types, so you can use:
dictionary.reduce(0) { $0 + $1.1.list.count }
Or, you can get just the values from the dictionary and reduce that:
dictionary.values.reduce(0) { $0 + $1.list.count }
Note that since Dictionary.values returns a lazy iterator, there's not really a huge cost to using it.
More simple and clear way goes like this,
var dict = ["x" : 1 , "y" : 2, "z" : 3]
let count = dict.reduce(0, { x, element in
//maybe here some condition
//if(element.value > 1){return x}
return x + 1
})

Immutable Dictionary value change

Can we change any pair value in let type Dictionary in Swift Langauage.
like :
let arr2 : AnyObject[] = [1, "23", "hello"]
arr2[1] = 23
arr2 // output: [1,23,"hello"]
let arr1 :Dictionary<Int,AnyObject> = [1: "One" , 2 : 2]
arr1[2] = 4 // not posible error
arr1
In Case of Immutable Array we can change its value like above but not in case of Immutable
Dictionary. Why?
This is taken from The Swift Programming Language book:
For dictionaries, immutability also means that you cannot replace the
value for an existing key in the dictionary. An immutable dictionary’s
contents cannot be changed once they are set.
Immutability has a slightly different meaning for arrays, however. You
are still not allowed to perform any action that has the potential to
change the size of an immutable array, but you are allowed to set a
new value for an existing index in the array.
Array declared with let has only immutable length. Contents can still be changed.
Dictionary declared with let is completely immutable, you can't change contents of it. If you want, you must use var instead of let.
Swift has changed a lot since then.
Array and Dictionary are value types. When declared with let, they cannot change any more. Especially, one cannot re-assign them, or the elements in them.
But if the type of the elements is reference type, you can change the properties of the elements in Array or Dictionary.
Here is a sample.(run in Xcode6 beta-6)
class Point {
var x = 0
var y = 0
}
let valueArr: [Int] = [1, 2, 3, 4]
let refArr: [Point] = [Point(), Point()]
valueArr[0] = -1 // error
refArr[0] = Point() // error
refArr[0].x = 1
let valueDict: [Int : Int] = [1: 1, 2: 2]
let refDict: [Int: Point] = [1: Point(), 2: Point()]
valueDict[1] = -1 //error
refDict[1] = Point() //error
refDict[1]!.x = -1

Not able to print values of array in swift

I am not able to print array values in swift. My code is:
var array = 1...10
println(array)
The result is:
VSs5Range (has 2 children)
But when I try to print the following array, it works:
var array = [1,2,3,4,5,6,7,8,9,10]
println(array)
Result is:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Why isn't the first one printing correctly?
The expression 1...10 returns a Range, not an Array. Internally, a Range stores two values (a start and an end); an Array, on he other hand, is a dynamic structure containing "n" values.
As explained,
var array = 1...10
array, in this case, is a Range object, not an array
If you want to print its content do this (changed the name to something more suitable)
var range = 1...10
for value in range
{
println(value)
}