I suspect this point has been discussed in length, but I would like to find some reference to the design logic behind some Swift key aspect : the assignment operator, by value or reference.
We know well how = works, depending it deals with reference or value (knowing the consequence of misuse) and the difference between the 2 :
Hence my question.
Was it ever considered to have 2 operators, one used to assign reference and the other to assign value?
Imagine we have :
= operator when dealing with references
:= operator when dealing with content.
Then
would remain unchanged.
But
would not be valid anymore, with a compiler warning to replace by
On the other end, we could now write
to create a new instance and assign another instance content, equivalent to convenience initialiser
called as
But the 2 operators would have made it clear that when using = we copy the reference. When using := we copy content.
I do think there is a strong rationale behind the present design choice (side effects I do not see ?), but I would appreciate to better understand which.
We know well how = works, depending it deals with reference or value (knowing the consequence of misuse) and the difference between the 2 :
Code Block class AClass { var val: Int = 0 } struct AStruct { var val : Int = 0 } let aClass = AClass() let bClass = aClass bClass.val += 10 print("aClass.val", aClass.val, "bClass.val", bClass.val) let aStruct = AStruct() var bStruct = aStruct bStruct.val += 10 print("aStruct.val", aStruct.val, "bStruct.val", bStruct.val)
Hence my question.
Was it ever considered to have 2 operators, one used to assign reference and the other to assign value?
Imagine we have :
= operator when dealing with references
:= operator when dealing with content.
Then
Code Block let bClass = aClass
would remain unchanged.
But
Code Block var bStruct = aStruct
would not be valid anymore, with a compiler warning to replace by
Code Block var bStruct := aStruct
On the other end, we could now write
Code Block let bClass := aClass
to create a new instance and assign another instance content, equivalent to convenience initialiser
Code Block class AClass { var val: Int = 0 init(with aVar: AClass) { self.val = aVar.val } init() { } }
called as
Code Block let cClass = AClass(with: aClass)
But the 2 operators would have made it clear that when using = we copy the reference. When using := we copy content.
I do think there is a strong rationale behind the present design choice (side effects I do not see ?), but I would appreciate to better understand which.