Swift — Structs
Basic struct
struct Point {
var x: Double
var y: Double
func distance(to other: Point) -> Double {
let dx = x - other.x
let dy = y - other.y
return sqrt(dx * dx + dy * dy)
}
}
let p1 = Point(x: 0, y: 0)
let p2 = Point(x: 3, y: 4)
print(p1.distance(to: p2)) // 5.0
Properties
struct Temperature {
var celsius: Double {
didSet {
print("Temperature set to \(celsius)°C")
}
}
var fahrenheit: Double {
get { celsius * 9 / 5 + 32 }
set { celsius = (newValue - 32) * 5 / 9 }
}
}
var t = Temperature(celsius: 100)
print(t.fahrenheit) // 212.0
t.fahrenheit = 32
print(t.celsius) // 0.0
Methods
struct Counter {
var count = 0
mutating func increment() {
count += 1
}
mutating func reset() {
count = 0
}
}
var c = Counter()
c.increment()
c.increment()
print(c.count) // 2
Initializers
struct Size {
var width: Double
var height: Double
init(width: Double = 0, height: Double = 0) {
self.width = width
self.height = height
}
}
let s1 = Size(width: 10, height: 5)
let s2 = Size() // 0, 0
Value semantics
struct Point {
var x: Double
var y: Double
}
let p1 = Point(x: 1, y: 2)
var p2 = p1
p2.x = 10
print(p1.x) // 1 (unchanged)
print(p2.x) // 10
Protocol conformance
struct Point: CustomStringConvertible {
var x: Double
var y: Double
var description: String {
"(\(x), \(y))"
}
}
let p = Point(x: 3, y: 4)
print(p) // (3.0, 4.0)
Mini Practice
Write Swift code that:
- Creates a struct with computed properties
- Uses
mutatingmethods - Demonstrates value semantics
- Conforms to a protocol
Up Next
In the next lesson, you'll learn about Classes — reference types in Swift.
Related Topics
Frequently Asked Questions about Structs
What is Structs in Swift?
Structs is a fundamental concept in Swift. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Structs?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Structs.
Why is Structs important in Swift?
Structs is essential for Swift development. Understanding this concept will help you write better code and solve real-world problems more effectively.