Swift Methods

Swift methods are functions that are associated with a particular type.

In Objective-C, classes are the only type that can define methods. In Swift, however, you can not only choose whether to define a class/struct/enum, but also flexibly define methods on the types you create (class/struct/enum).


Instance Methods

In Swift, instance methods are methods that belong to instances of a particular class, structure, or enumeration type.

Instance methods provide the following capabilities:

  • They can access and modify instance properties

  • Provide functionality related to the purpose of the instance

Instance methods must be written between the opening and closing braces ({}) of the type to which they belong.

Instance methods can implicitly access all other instance methods and properties of the type to which they belong.

Instance methods can only be called on a particular instance of the class to which they belong.

Instance methods cannot be called independently of an existing instance.

Syntax

func funcname(Parameters) -> returntype
{
    Statement1
    Statement2
    ……
    Statement N
    return parameters
}

Example

import Cocoa

class Counter {
    var count = 0
    func increment() {
        count += 1
    }
    func incrementBy(amount: Int) {
        count += amount
    }
    func reset() {
        count = 0
    }
}
// 初始计数值是0
let counter = Counter()

// 计数值现在是1
counter.increment()

// 计数值现在是6
counter.incrementBy(amount: 5)
print(counter.count)

// 计数值现在是0
counter.reset()
print(counter.count)

The output of the above program is:

6
0

The Counter class defines three instance methods:

  • incrementIncrement the counter by 1;
  • incrementBy(amount: Int)Increment the counter by a specified integer value;
  • resetReset the counter to 0.

CounterThe class also declares a variable propertycountto keep track of the current counter value.


Local and External Parameter Names for Methods

Swift function parameters can have both a local name (used within the function body) and an external name (used when calling the function).

Methods in Swift are extremely similar to methods in Objective-C. As in Objective-C, the name of a method in Swift usually uses a preposition to refer to the method's first parameter, such as with, for, by, etc.

By default, Swift gives only the first parameter name a local parameter name; by default, it gives the second and subsequent parameter names external parameter names.

In the following example, 'no1' is declared as a local parameter name in Swift. 'no2' is declared as an external parameter name and accessed by external code.

import Cocoa

class division {
    var count: Int = 0
    func incrementBy(no1: Int, no2: Int) {
        count = no1 / no2
        print(count)
    }
}

let counter = division()
counter.incrementBy(no1: 1800, no2: 3)
counter.incrementBy(no1: 1600, no2: 5)
counter.incrementBy(no1: 11000, no2: 3)

The output of the above program is:

600
320
3666

Specifying External Parameter Names

We force an external name for the first parameter by treating the local name as the external name (before Swift 2.0, the # symbol was used).

Conversely, we can also use an underscore (_) to set the second and subsequent parameters so that they do not provide an external name.
import Cocoa

class multiplication {
    var count: Int = 0
    func incrementBy(first no1: Int, no2: Int) {
        count = no1 * no2
        print(count)
    }
}

let counter = multiplication()
counter.incrementBy(first: 800, no2: 3)
counter.incrementBy(first: 100, no2: 5)
counter.incrementBy(first: 15000, no2: 3)

The output of the above program is:

2400
500
45000

The self Property

Every instance of a type has an implicit property called self, which is exactly equivalent to the instance itself.

You can use this implicit self property within an instance method of an instance to refer to the current instance.

import Cocoa

class calculations {
    let a: Int
    let b: Int
    let res: Int
    
    init(a: Int, b: Int) {
        self.a = a
        self.b = b
        res = a + b
        print("Self 内: \(res)")
    }
    
    func tot(c: Int) -> Int {
        return res - c
    }
    
    func result() {
        print("结果为: \(tot(c: 20))")
        print("结果为: \(tot(c: 50))")
    }
}

let pri = calculations(a: 600, b: 300)
let sum = calculations(a: 1200, b: 300)

pri.result()
sum.result()

The output of the above program is:

Self 内: 900
Self 内: 1500
结果为: 880
结果为: 850
结果为: 1480
结果为: 1450

Modifying Value Types from Within Instance Methods

In Swift, structures and enumerations are value types. By default, the properties of a value type cannot be modified from within its instance methods.

However, if you really need to modify the properties of a structure or enumeration in a specific method, you can choose to mark the method as mutating. The method can then change its properties from within the method; and any changes it makes are retained in the original structure when the method ends.

A method can also assign a completely new instance to its implicit self property, and this new instance will replace the original instance when the method ends.

import Cocoa

struct area {
    var length = 1
    var breadth = 1
    
    func area() -> Int {
        return length * breadth
    }
    
    mutating func scaleBy(res: Int) {
        length *= res
        breadth *= res
        
        print(length)
        print(breadth)
    }
}

var val = area(length: 3, breadth: 5)
val.scaleBy(res: 3)
val.scaleBy(res: 30)
val.scaleBy(res: 300)

The output of the above program is:

9
15
270
450
81000
135000

Assigning to self Within a Mutating Method

A mutating method can assign an entirely new instance to the implicit self property.

import Cocoa

struct area {
    var length = 1
    var breadth = 1
    
    func area() -> Int {
        return length * breadth
    }
    
    mutating func scaleBy(res: Int) {
        self.length *= res
        self.breadth *= res
        print(length)
        print(breadth)
    }
}
var val = area(length: 3, breadth: 5)
val.scaleBy(res: 13)

The output of the above program is:

39
65

Type Methods

Instance methods are methods called by an instance of a type. You can also define methods that are called by the type itself, and such methods are called type methods.

To declare type methods for structures and enumerations, add the keyword static before the func keyword of the method. Classes may use the keyword class to allow subclasses to override the superclass's implementation of the method.

Type methods are called using dot (.) syntax, just like instance methods.

import Cocoa

class Math
{
    class func abs(number: Int) -> Int
    {
        if number < 0
        {
            return (-number)
        }
        else
        {
            return number
        }
    }
}

struct absno
{
    static func abs(number: Int) -> Int
    {
        if number < 0
        {
            return (-number)
        }
        else
        {
            return number
        }
    }
}

let no = Math.abs(number: -35)
let num = absno.abs(number: -5)

print(no)
print(num)

The output of the above program is:

35
5
Other Extensions