Methods

A method is a function attached to a type. You call it on an instance with dot syntax, and self refers to that instance.

Instance methods

Methods can be written directly in the struct body or in extend blocks; this page uses extend:

struct Circle { let radius: Float64 } extend Circle { func area() -> Float64 { 3.14159 * self.radius * self.radius } } let c = Circle(radius: 2.0); let a = c.area();

self refers to the instance the method is called on. You don't declare it as a parameter — it's implicit.

Mutating methods

A method that writes to a var field must be marked mutating:

struct Counter { var value: Int } extend Counter { mutating func increment() { self.value = self.value + 1; } } var c = Counter(value: 0); c.increment(); // c.value is now 1

The caller has to hold the instance via var — same rule as mutating parameters. See Access Modes.

Static methods

A method that doesn't need an instance — usually a constructor or a utility — is static:

struct Point { let x: Int let y: Int } extend Point { static func origin() -> Point { Point(x: 0, y: 0) } } let p = Point.origin();

Call it on the type, not an instance.

Methods are still functions

A method is a function with an implicit first parameter. They can have labels, return values, generics, and constraints just like any other function:

protocol VectorLike { func xValue() -> Float64 func yValue() -> Float64 } struct Vector { let x: Float64 let y: Float64 } extend Vector: VectorLike { public func xValue() -> Float64 { self.x } public func yValue() -> Float64 { self.y } } extend Vector { func dot[T](with other: T) -> Float64 where T: VectorLike { self.x * other.xValue() + self.y * other.yValue() } } let v1 = Vector(x: 1.0, y: 2.0); let v2 = Vector(x: 3.0, y: 4.0); v1.dot(with: v2); // 11

For the broader function story (labels, access modes, closures), see the Functions overview. For struct-side method coverage including initializers and computed properties, see Structs.