Sobes.tech
Junior

Tell me about two semantics in the Swift language.

sobes.tech AI

Answer from AI

Swift supports both value semantics and reference semantics.

  1. Value Semantics:

    • When assigning or passing to a function, a copy of the value is created.
    • Modifying the copy does not affect the original.
    • Used for structures (struct), enumerations (enum), and tuples (tuple).
    • Ensures predictable behavior and thread safety when working with immutable data.
    struct Point {
        var x: Int
        var y: Int
    }
    
    var p1 = Point(x: 1, y: 2)
    var p2 = p1 // Copy occurs
    
    p2.x = 10 // Modifying the copy
    
    print(p1.x) // Will print 1, original remains unchanged
    
  2. Reference Semantics:

    • When assigning or passing to a function, a reference to the same object in memory is passed.
    • Changing the object through any reference affects all other references to that object.
    • Used for classes (class).
    • Allows inheritance and polymorphism.
    class Circle {
        var radius: Double
    
        init(radius: Double) {
            self.radius = radius
        }
    }
    
    var c1 = Circle(radius: 5.0)
    var c2 = c1 // Reference copy occurs
    
    c2.radius = 10.0 // Changing the object via reference
    
    print(c1.radius) // Will print 10.0, original has changed
    
Tell me about two semantics in the Swift language… - sobes.tech