Swift Language Functions Methods

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

Instance methods are functions that belong to instances of a type in Swift (a class, struct, enumeration, or protocol). Type methods are called on a type itself.

Instance Methods

Instance methods are defined with a func declaration inside the definition of the type, or in an extension.

class Counter {
    var count = 0
    func increment() {
        count += 1
    }
}

The increment() instance method is called on an instance of the Counter class:

let counter = Counter()  // create an instance of Counter class   
counter.increment()      // call the instance method on this instance

Type Methods

Type methods are defined with the static func keywords. (For classes, class func defines a type method that can be overridden by subclasses.)

class SomeClass {
    class func someTypeMethod() {
        // type method implementation goes here
    }
}
SomeClass.someTypeMethod()  // type method is called on the SomeClass type itself


Got any Swift Language Question?