Junior
What are value types in Swift and how do they relate to data types?
sobes.tech AI
Answer from AI
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.
Value types in Swift 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)
- Numeric types (
Example:
struct Point {
var x: Int
var y: Int
}
var p1 = Point(x: 1, y: 2)
var p2 = p1 // Copying the value of p1 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 changing p2: \(p2.x), \(p2.y)") // p2 after changing p2: 10, 2