Methods
methods are functions that are associated with particular types.
Instance methods
Instance methods are functions that belongs to the instance of particular class, structure, enumeration.
class Counter {
var count = 0
func increment() {
count += 1
}
}
//increment method is an instance method
The 'self' property
Every property of a type has an implicit property called self, which is exactly equivalent to the instance itself.
func increment() {
self.count += 1
}
Modifying Value Types from Within Instance Methods
Structures and enumerations are value types. By default, the properties of a value type can’t be modified from within its instance methods.
However, if you need to modify the properties of your structure or enumeration within a particular method, you can opt in to mutating behavior for that method.
struct Point {
var x = 0.0, 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)
Type Methods
Instance methods, as described above, are methods that you call on an instance of a particular type. You can also define methods that are called on the type itself. These kinds of methods are called type methods. You indicate type methods by writing the static keyword before the method’s func keyword. Classes can use the class keyword instead.
class SomeClass {
class func someTypeMethod() {
// type method implementation goes here
}
}
SomeClass.someTypeMethod()
Top comments (0)