Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assignment always make copying in swift

Tags:

swift

assign

var list1 = [1, 2, 3, 4, 5]
var list2 = list1
list2.removeLast()
println(list1)
println(list2)

This is a simple code that just:

  1. assign the list1 to list2
  2. remove object from list2
  3. that object is removed from list2 BUT STILL EXIST IN list1

It seems that the assignment make something like copying but not assign the pointer.

I want to know if there is any official documents explain about it and how to make it enter code here

like image 715
debuggenius Avatar asked Sep 11 '14 07:09

debuggenius


2 Answers

An array is a struct, and structs are value types, so they are copied by value and not by reference. The same happens for dictionaries, a copy is created if you assign to another variable.

Classes instead are reference types, and assignment copies the reference to the instance.

You can read more about that in Structures and Enumerations Are Value Types

Sidenote: a struct passed to a function is immutable - you cannot modify it within the function, unless you pass it by reference using the inout attribute

like image 58
Antonio Avatar answered Oct 29 '22 22:10

Antonio


Yes the Apple Swift documentation explains that Swift array (dictionary as well) is a struct, not an object and struct are copied when they are passed around in the code. If you create struct they are always copied. If you want to pass it by reference instead you should create class.

like image 41
Greg Avatar answered Oct 29 '22 21:10

Greg