Swift — Methods
Instance methods
class Counter {
var count = 0
func increment() {
count += 1
}
func increment(by amount: Int) {
count += amount
}
func reset() {
count = 0
}
}
let c = Counter()
c.increment()
c.increment(by: 5)
print(c.count) // 6
Mutating methods
struct Point {
var x: Double
var y: Double
mutating func moveBy(dx: Double, dy: Double) {
x += dx
y += dy
}
}
var p = Point(x: 0, y: 0)
p.moveBy(dx: 3, dy: 4)
print(p) // Point(x: 3.0, y: 4.0)
Type methods
class MathHelper {
static func square(_ x: Int) -> Int {
x * x
}
static let pi = 3.14159
}
print(MathHelper.square(5)) // 25
print(MathHelper.pi)
Self
struct Point {
var x: Double
var y: Double
func isOrigin() -> Bool {
self.x == 0 && self.y == 0
}
}
let p = Point(x: 0, y: 0)
print(p.isOrigin()) // true
Mini Practice
Write Swift code that:
- Creates a class with instance methods
- Uses a
mutatingmethod on a struct - Creates a type method with
static - Demonstrates
selfkeyword
Up Next
In the next lesson, you'll learn about Protocols — defining contracts in Swift.
Related Topics
Frequently Asked Questions about Methods
What is Methods in Swift?
Methods 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 Methods?
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 Methods.
Why is Methods important in Swift?
Methods is essential for Swift development. Understanding this concept will help you write better code and solve real-world problems more effectively.