Sobes.tech
Junior

Mis on value types Swiftis ja kuidas nad on seotud andmetüüpidega?

sobes.tech AI

Vastus AI-lt

Value types in Swift are types whose value is copied when assigned to a variable or constant, as well as when passed to a function. Each instance of a value type stores its own copy of data.

In Swift, value types include:

  • Structures (struct)
  • Enumerations (enum)
  • Tuples (tuple)
  • Basic data types:
    • Numeric types (Int, Double, Float, Bool, etc.)
    • Strings (String)
    • Arrays (Array)
    • Dictionaries (Dictionary)
    • Sets (Set)

Example:

struct Point {
    var x: Int
    var y: Int
}

var p1 = Point(x: 1, y: 2)
var p2 = p1 // Copy of p1's value into p2
print("p1: \(p1.x), \(p1.y)") // p1: 1, 2
print("p2: \(p2.x), \(p2.y)") // p2: 1, 2

p2.x = 10 // Changing p2 does not affect p1
print("p1 after changing p2: \(p1.x), \(p1.y)") // p1 after changing p2: 1, 2
print("p2 after change: \(p2.x), \(p2.y)") // p2 after change: 10, 2