← Back to Swift Course | Chapter 8: Structs & Classes | Lesson 7 of 9

Methods

A method is just a function that belongs to a struct or class, giving that type its own actions it can perform.

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

markup
struct Circle {
    var radius: Double
    func area() -> Double {
        return Double.pi * radius * radius
    }
}
let circle = Circle(radius: 3)
print("Area: \(circle.area())")

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

markup
struct MathHelper {
    static func square(_ n: Int) -> Int {
        return n * n
    }
}
print(MathHelper.square(6))
Common Mistakes
  1. 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.
  2. Calling an instance method as if it were a type-level (static) method, or vice versa.
  3. 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 static method 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.