Latest web development tutorials

Swift Methods

Swift is a function of the method associated with certain types

In Objective-C, classes are the only type defined methods. But Swift, you not only can choose whether you want to define a class / struct / enum, but also flexible in type (class / struct / enum) that you create on the definition method.


Instance Methods

In Swift language, an instance method belongs to a particular class, a structure or enumerated type instances.

Instance method provides the following methods:

  • You can access and modify instance properties

  • Example providing object-related functions

Examples of methods to write around it belongs between the types of braces ({}).

Examples of implicit method can access all methods and properties of other instances of the type to which it belongs.

Examples of methods can only be called a particular instance of the class to which it belongs.

Instance method can not be separated on the existing instance is called.

grammar

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

Examples

import Cocoa

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

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

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

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

The above program execution output is:

6
0

Counter class defines three instance methods:

  • increment so that the counter is incremented by one;
  • incrementBy(amount: Int) make counter by a specified integer value is incremented;
  • reset the counter is reset to 0.

Counter This class also declares a variable attribute count , use it to keep track of the current counter value.


Local parameter name and the name of the method the external parameters

Swift function parameters can have both a local name (in the body of the function used internally) and an external name (used when calling functions

Swift methods and Objective-C method very similar. Like in Objective-C, the same as the name of Swift in the method usually a preposition points to the first parameter method, for example: with, for, by, and so on.

Swift default only to the method of the first parameter the name of a local parameter name; the default at the same time to the second and subsequent global parameter name parameter name.

The following examples 'no1' declared locally in the parameter name in the swift. 'No2' for global declarations and accessed through an external program.

import Cocoa

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

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

The above program execution output is:

600
320
3666

Whether to provide external name settings

We force the first argument to add an external name to the name of the local name as external use (Swift 2.0 before using the # sign).

Instead, we can use it also underscores (_) to set the second and subsequent arguments 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 above program execution output is:

2400
500
45000

self property

Each instance of the type has a property called implicit self, self exactly the same as the instance itself.

You can use this implicit self a property in an instance method instance to reference 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(20))")
        print("结果为: \(tot(50))")
    }
}

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

pri.result()
sum.result()

The above program execution output is:

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

Modify the value type instance method

Swift language structures, and enumerations are value types. In general, the type of the property value can not be modified in its instance methods.

But if you really need to change the structure or enumerated property in a specific way, you can choose the variation (mutating) the method, then the method can change the properties from the internal method; any changes, and it does at the end of the method it will be left in the original structure.

The method also can give it implied self property assignment a new instance of this new instance to replace the original instance with method.

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(3)
val.scaleBy(30)
val.scaleBy(300)

The above program execution output is:

9
15
270
450
81000
135000

In the process variable assigned to self

Variable method can assign attributes self implied a new instance.

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(13)

The above program execution output is:

39
65

Type methods

Instance method is a method is called an instance of the type, you can also define the type of method calls itself, this method is called type method.

Statement structure and enumerated type method before func keyword method with the keyword static. Class might use the keyword class to allow subclasses override the parent class implementation.

The same type and instance methods using the dot (.) Syntax to invoke.

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(-35)
let num = absno.abs(-5)

print(no)
print(num)

The above program execution output is:

35
5