Methods
A method is just a function that belongs to a struct or class, giving that type its own actions it can perform.
In this page:
Defining an Instance Method
An instance method is declared with func inside a type, and is called on a specific instance of that type using dot syntax.
Example: Defining an Instance Method
struct Circle {
var radius: Double
func area() -> Double {
return Double.pi * radius * radius
}
}
let circle = Circle(radius: 3)
print("Area: \(circle.area())")
Login to try C/C++/Java/PHP code in the editor
Static Methods
A static method belongs to the type itself, not to any particular instance, and is called directly on the type name.
Example: Static Methods
struct MathHelper {
static func square(_ n: Int) -> Int {
return n * n
}
}
print(MathHelper.square(6))
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Forgetting a struct's method that modifies a property must be explicitly marked
mutating; classes never need this since their methods can always modify properties. - Calling an instance method as if it were a type-level (static) method, or vice versa.
- Overusing
self.when it's not needed for disambiguation; Swift often infers it from context, though it's required inside closures and some initializers.
Chapter Summary
- An instance method is a function defined inside a struct or class, called on an instance.
- A
staticmethod belongs to the type itself rather than any single instance. - Struct methods that modify properties must be marked
mutating. - Class methods can always modify properties without any special keyword.
🔒
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: