Structs are Swift’s preferred way to model most data—value semantics, automatic memberwise initializers, and copy-on-write performance. Unlike Java classes, structs are copied by assignment.
Defining and using structs
struct Point {
var x: Double
var y: Double
func distance(from other: Point) -> Double {
let dx = x - other.x
let dy = y - other.y
return (dx*dx + dy*dy).squareRoot()
}
}
var a = Point(x: 0, y: 0)
var b = a
b.x = 3
print(a.x) // still 0
Compared to Kotlin data classes
Kotlin data class on JVM is reference-typed; Swift structs are true value types—important for reasoning about mutation and threading.
Important interview questions and answers
- Q: Struct vs class?
A: Structs are value types copied on assignment; classes are reference types with ARC—prefer structs for models unless you need inheritance or shared identity. - Q: Can structs have methods?
A: Yes—methods, computed properties, and protocol conformance are all supported.
Self-check
- What happens to
awhen you mutate copyb? - When should you choose a class over a struct?
Tip: Default to structs for models—value semantics simplify reasoning vs reference types.
Interview prep
- Struct vs class?
Struct value semantics copied on assignment; class reference semantics with ARC.
- When prefer struct?
Default for models and value data—most Swift APIs start here.