Junior — Middle
What are the differences between data types in terms of their semantics: values and references?
sobes.tech AI
Answer from AI
Data types by semantics are divided into value types and reference types.
-
Value types store data directly. When assigned or passed to a function, the value itself is copied. In iOS (Swift), examples include
Int,Double,Bool, and structures (struct). -
Reference types store a reference to a memory area where the data resides. When assigned, the reference is copied, not the data. Changes through one reference are visible through others. In Swift, these are classes (
class) and objects.
Example:
struct Point { var x: Int; var y: Int }
class Person { var name: String
init(name: String) { self.name = name } }
var p1 = Point(x: 1, y: 2)
var p2 = p1
p2.x = 10
print(p1.x) // 1 — copy did not change
var person1 = Person(name: "Ivan")
var person2 = person1
person2.name = "Peter"
print(person1.name) // "Peter" — reference to the same object
Understanding the difference is important for memory management and object behavior in an application.