Use Methods in Swift
Written by Team Kodeco
Methods in Swift are functions that are associated with an instance of a class or structure. They can be used to perform actions or calculations on the properties of an object and can also take parameters and return values.
Here’s an example of how to define a method in a class:
class MyClass {
var myProperty: Int
init(propertyValue: Int) {
self.myProperty = propertyValue
}
func doubleMyProperty() {
myProperty *= 2
}
}
This creates a new class called MyClass
with a method called doubleMyProperty
that doubles the value of the myProperty
property.
You can call the method on an instance of the class like this:
let myObject = MyClass(propertyValue: 10)
myObject.doubleMyProperty()
print(myObject.myProperty) // prints "20"
Here’s an example of how to define a method that takes parameters and returns a value in a structure:
import Foundation
struct Point {
var x: Double
var y: Double
init(x: Double, y: Double) {
self.x = x
self.y = y
}
func distance(to point: Point) -> Double {
let deltaX = x - point.x
let deltaY = y - point.y
return sqrt(deltaX * deltaX + deltaY * deltaY)
}
}
This creates a new structure called Point
with a method called distance
that takes one parameter of Point
type and returns the distance between two points.
You can call the method on an instance of the structure like this:
let point1 = Point(x: 0.0, y: 0.0)
let point2 = Point(x: 3.0, y: 4.0)
let distance = point1.distance(to: point2)
print(distance) // prints "5.0