Method
Methods are functions that are associated with a particular type. In Swift, you can define methods for classes, structures, and enumerations. Methods are used to provide functionality for manipulating or interacting with an object's properties.
Instance Methods
Instance methods are functions that belong to instances of a particular class, structure, or enumeration. They have access to self, which refers to the instance the method is being called on.
Here's a simple example:
class Counter {
var count = 0
func increment() {
count += 1
}
func increment(by amount: Int) {
count += amount
}
func reset() {
count = 0
}
}
let counter = Counter()
counter.increment()
print(counter.count) // Output: 1
counter.increment(by: 5)
print(counter.count) // Output: 6
counter.reset()
print(counter.count) // Output: 0
Type Methods
Type methods are methods that are called on the type itself rather than on instances. You define type methods with the static keyword for structures and enumerations and with either the static or class keyword for classes. If you use class, you can allow a method to be overridden by subclasses.
Here's an example with a type method:
class Math {
static func square(of number: Int) -> Int {
return number * number
}
class func cube(of number: Int) -> Int {
return number * number * number
}
}
print(Math.square(of: 5)) // Output: 25
print(Math.cube(of: 3)) // Output: 27
mutating Methods in Value Types
Since structures and enumerations are value types, their properties cannot be modified within their instance methods by default. If you need to modify the properties, you have to mark the method with the mutating keyword.
struct Point {
var x = 0.0
var y = 0.0
mutating func moveBy(x deltaX: Double, y deltaY: Double) {
x += deltaX
y += deltaY
}
}
var somePoint = Point(x: 1.0, y: 1.0)
somePoint.moveBy(x: 2.0, y: 3.0)
print("The point is now at (\(somePoint.x), \(somePoint.y))") // Output: The point is now at (3.0, 4.0)
self Property
In any instance method, self refers to the instance itself. It is particularly useful to distinguish between a parameter name and a property name if they are the same.
struct Point {
var x = 0.0
var y = 0.0
func isToTheRightOf(x: Double) -> Bool {
return self.x > x
}
}
Methods in Enumerations
Enumerations can also have methods associated with them.
enum TriStateSwitch {
case off, low, high
mutating func next() {
switch self {
case .off:
self = .low
case .low:
self = .high
case .high:
self = .off
}
}
}
Method Parameters and Return Types
Just like normal functions, methods can take parameters and return values:
class Calculator {
func multiply(_ a: Int, by b: Int) -> Int {
return a * b
}
}
let calculator = Calculator()
print(calculator.multiply(3, by: 4)) // Output: 12
Methods in Swift are flexible and versatile, allowing you to encapsulate behavior in a clean and organized manner. They make your types more expressive and easier to use, both as standalone entities and as part of larger, more complex types.