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:
Syntax
struct TypeName {
func methodName(param: Type) -> ReturnType {
return value
}
static func typeMethod() { }
}
instance.methodName(param: value)
TypeName.typeMethod()
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
// Define a struct `Circle`
struct Circle {
var radius: Double
// Define the function `area` with no parameters and returning a Double
func area() -> Double {
// Return `Double.pi * radius * radius` from this function
return Double.pi * radius * radius
}
}
// Declare a constant `circle`, set to `Circle(radius: 3)`
let circle = Circle(radius: 3)
// Print "Area: \(circle.area())" to the console
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
// Define a struct `MathHelper`
struct MathHelper {
static func square(_ n: Int) -> Int {
// Return `n * n` from this function
return n * n
}
}
// Print `MathHelper.square(6)` to the console
print(MathHelper.square(6))
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
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: