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
Related
In a Mozilla developer translated Korean lang says 'slice method' returns a new array copied shallowly.
so I tested my code.
var animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
var t = animals.slice(2,4);
console.log(t);
t[0] = 'aaa';
console.log(t);
console.log(animals);
but, If slice method returns shallow array, the animals array should be changed with ['ant', 'bison', 'aaa', 'duck', 'elephant'].
Why is it shallow copy?
slice does not alter the original array.
It returns a shallow copy of elements from the original array.
Elements of the original array are copied into the returned array as follows:
For object references (and not the actual object), slice copies object references into the new array. Both the original and new array refer to the same object. If a referenced object changes, the changes are visible to both the new and original arrays.
For strings, numbers and booleans (not String, Number and Boolean objects), slice copies the values into the new array. Changes to the string, number or boolean in one array do not affect the other array.
If a new element is added to either array, the other array is not affected.(source)
In your case the the array consists of strings which on slice would return new strings copied to the array thus is a shallow copy.
In order to avoid this use the object form of array.
strings are primitive types in JavaScript, so you will get a new array with new strings inside.
Your test array should be an array of objects:
var animals = [{name: 'ant'}, {name: 'bison'}, {name: 'camel'}, {name: 'duck'}, {name: 'elephant'}];
var t = animals.slice(2,4);
console.log(t);
t[0].name = 'aaa';
console.log(t);
console.log(animals);
The slice method doesn't change the original array or string. It only cuts a portion of the original string or array and returns it as a copy.
For more understanding of it, kindly check this video below:
https://youtu.be/mUH8hPQfMbg [Slice method made easy for absolute beginners]
May be you are looking for this. Try this!
let animals = ['ant', 'bison', 'camel', [1, 2]];
let t = animals.slice();
t[0] = 'aaa'; // string (primitive datatype)
t[t.length-1][0] = 0; // array (object)
console.log(t);
console.log(animals);
In case of a shallow copy-
Objects will reflect change in the original place from where they were shallowly copied because they are stored as references (to their address in the Heap).
Primitive data types will NOT reflect change in the original place because they are directly stored in the callstack (in Execution Contexts).
I have a Dictionary from which I need to have all keys plus one in an Array.
I thought:
let keysArray = Array(dictionary.keys).append("OneMoreKey")
would work. But it results in: Cannot use mutating member on immutable value: function call returns immutable value.
What is the nicest way to do this?
You can append to the array of keys by doing:
let keysArray = Array(dictionary.keys) + ["OneMoreKey"]
The problem with append is that it is attempting to mutate the non-variable array of keys.
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.
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
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