I want to store a reference to an array element and modify the array element using the reference.
Example Code:
var myArray : [String] = ["foo"]
var element = myArray.first!
element.append("bar")
print(myArray.first!)
Expected Output:
> foobar
Actual Output:
> foo
My expectation was that first would return a reference to the array element. Instead, Swift returns a copy of the element, meaning the array element doesn't get modified.
Is there a way to store a reference to an array element using Swift arrays?
Swift's String is a value type, so it returns a copy not a reference, if you want to get a reference you should use NSString not String.
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).
String[] arr = new String[10];
This creates an array with 10 elements all set to null. The first null element can be accessed with arr[0]
ArrayList<String> arr2 = new ArrayList<String>[10];
This creates an array with capacity of 10 but apparently no elements. Is this why you cannot use arr2.get(0) which returns an error? Because there are no elements present?
An ArrayList is a class and an object to the class should be created using a constructor
ArrayList<String>[10] produces an error: cannot create array with '<>' error
Using constructor, the ArrayList is constructed as ArrayList<String>(10);
It is to be noted that this statement creates an Empty ArrayList of initial size 10.
The ArrayList only gets populated when you push values into it.
Refer the following for more understanding:
[1] [2] [3]
let nameArray = ["ramesh","suresh","rajesh"]
let idArray = ["100","101","102"]
Now i want value of "idArray" by using index value of "nameArray".
if nameArray index is 0. Output is 100
In Object Oriented Programming, objects should own their properties. So instead of having two data structures describe the same object, either use structs like Mr. Vadian has suggested, or have one array store all the properties of the objects:
let zippedArray = Array(zip(nameArray, idArray))
And now to get the object in a given index, you can use the following:
let index = 0
let element = zippedArray[0]
print(element.0) //ramesh
print(element.1) //100
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 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