Skip to content

Latest commit

 

History

History
58 lines (42 loc) · 1.87 KB

File metadata and controls

58 lines (42 loc) · 1.87 KB

Methods in Swift

Table Of Contents

  1. What's the Difference Between a Function and a Method?
  2. Instance Methods and Type Methods
    1. Instance Methods
    2. Type Methods
  3. References

What's the Difference Between a Function and a Method?

  • A method is a function associated with a type.
  • Every method is a function.

Instance Methods and Type Methods

Let's consider the following example:

class Foo {
    init() {}
        
    func instanceMethod() {
        print("An instance method")
    }
    
    static func staticMethod() {
        print("A type method (static)")
    }
    
    class func classMethod() {
        print("A type method (class) that can be overridden in a subclass")
    }
}

let foo = Foo()
foo.instanceMethod()
Foo.staticMethod()
Foo.classMethod()

Instance Methods

  • An instance method can be called on an instance.
  • An instance method cannot be called on a type.

Type Methods

  • An type method can be called on a type.
  • An type method cannot be called on an instance.
  • Type methods can be defined using static and class keywords:
    • The class keyword is used in classes and actors when you want to override the method in a subclass.
    • The static keyword is used in enums and structs or in classes and actors when you do want to override the method in a subclass.

References