Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Swift Methods

Swift Methods

A method is a function associated with a particular type (class, struct, or enum), describing what that type can do.

The biggest difference from an ordinary function is that a method is called through an instance or a type and can directly access that instance's properties.


Instance Methods

An instance method belongs to a specific instance; it can read and modify that instance's properties and call other methods of the same type.

The Counter class below uses three instance methods to manage a counter.

Example

import Foundation

class

Counter

{

    var count

=

0

    func increment

(

)

{

        count

=

1

   

}

   

// Use _ to explicitly omit the external label, passing values directly when calling

    func incrementBy

(

_ amount

:

Int

)

{

        count

=

amount

   

}

    func reset

(

)

{

        count

=

0

   

}

}

let counter

=

Counter

(

)

counter.

increment

(

)

         

// The count becomes 1

counter.

incrementBy

(

5

)

     

// The count becomes 6

print

(

"Counter value: (counter.count)"

)

counter.

reset

(

)

print

(

"Value after reset: (counter.count)"

)

Running result:



计数器的值:6

重置后的值:0

An instance method can only be called on an instance of its type and cannot exist independently of an instance.


Parameter Label Rules for Methods

This is where Swift beginners most often make mistakes, so memorize the rules first.

Since Swift 3 (SE-0046), all parameters have external labels by default, including the first. That is, func greet(site: String) must be called as greet(site: "RUNOOB").

To make the external label different from the parameter name, write func f(label name: Type); to omit the label, use an underscore _ explicitly.

Syntax define called Description
Omitting Labels func greet(_ site: String) greet("RUNOOB") Using _ Explicitly omitting the external label
Default Label func greet(site: String) greet(site: "RUNOOB") The parameter name serves as both local name and external label
Custom labels func greet(to site: String) greet(to: "RUNOOB") to externally, site internally
Omitting Labels for Later Parameters func sum(_ a: Int, _ b: Int) sum(2, 3) The second and later parameters can also be omitted with _

The example below compares the three forms side by side.

Example

import Foundation

struct

Runoob

{

   

// 1. Use _ to explicitly omit the external label

    func greet

(

_ site

:

String

)

String

{

       

return

"Welcome to (site)"

   

}

   

// 2. Explicitly give the external label: label name

    func visit

(

to site

:

String, times count

:

Int

)

String

{

       

return

"Visited (site) (count) times"

   

}

   

// 3. Use _ to omit the external label for the second parameter as well

    func sum

(

_ a

:

Int, _ b

:

Int

)

Int

{

       

return

a

b

   

}

}

let r

=

Runoob

(

)

print

(

r.

greet

(

"RUNOOB"

)

)

print

(

r.

visit

(

to

:

"www.runoob.com"

, times

:

3

)

)

print

(

r.

sum

(

2

,

3

)

)

Running result:



欢迎来到 RUNOOB

访问 www.runoob.com 3 次

5

Note:Since Swift 3, the first parameter has an external label by default,func greet(site: String) It must use greet(site: "RUNOOB") when calling. To omit the label, write explicitly in the declaration _:func greet(_ site: String) so that you can write greet("RUNOOB"). "The first parameter has no external label by default" is an old Swift 2 rule, long since obsolete.


The self Property

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

When a parameter name matches a property name, use self to refer explicitly to the property, avoiding writing an assignment where the parameter assigns to itself.

Example

import Foundation

struct

Point

{

    var x

=

0.0

, y

=

0.0

   

// self distinguishes properties and parameters with the same name

    init

(

x

:

Double, y

:

Double

)

{

        self.

x

=

x

        self.

y

=

y

   

}

    func isToTheRightOf

(

_ other

:

Point

)

Bool

{

       

return

self.

x

other.

x

   

}

}

let a

=

Point

(

x

:

10.0

, y

:

10.0

)

let b

=

Point

(

x

:

5.0

, y

:

5.0

)

print

(

"a is to the right of b: (a.isToTheRightOf(b))"

)

print

(

"b is to the right of a: (b.isToTheRightOf(a))"

)

Running result:



a 在 b 的右侧:true

b 在 a 的右侧:false

When accessing its own properties in an instance method, you can usually omit self and Swift infers it; you only need to write it when disambiguating.


mutating Methods and Assigning to self

Structs and enums are value types, and by default instance methods cannot modify their own properties.

To let a method modify properties, add the mutating keyword before func.

A mutating method has an even stronger capability: it can replace the entire self with a brand-new instance.

Example

import Foundation

struct

Counter

{

    var count

=

0

    mutating func increment

(

)

{

        count

=

1

   

}

   

// Use self to replace the entire instance with a new one

    mutating func resetToZero

(

)

{

        self

=

Counter

(

)

   

}

   

// You can also replace it with a new instance with different properties

    mutating func doubled

(

)

{

        self

=

Counter

(

count

:

count

2

)

   

}

}

var c

=

Counter

(

)

c.

increment

(

)

c.

increment

(

)

print

(

"After increment: (c.count)"

)

c.

doubled

(

)

print

(

"After doubling: (c.count)"

)

c.

resetToZero

(

)

print

(

"After reset: (c.count)"

)

Running result:



递增后:2

翻倍后:4

重置后:0

Note:A mutating method can only be called on var instances declared with . With let declared struct instances, even if their properties are variables, mutating methods cannot be called.


Type Methods

A type method belongs to the type itself and can be called without creating an instance, accessed with dot syntax.

Type methods for structs and enums are declared with static; in classes you can use class to declare type methods that subclasses can override.

Example

import Foundation

struct

MathHelper

{

   

// Type methods of structs must use static

   

static

func

abs

(

_ number

:

Int

)

Int

{

       

return

number

<

0

?

number

:

number

   

}

}

class

Shape

{

    var name

:

String

    init

(

name

:

String

)

{

        self.

name

=

name

   

}

   

// Type methods marked with class can be overridden by subclasses

   

class

func description

(

)

String

{

       

return

"This is a shape"

   

}

   

static

func category

(

)

String

{

       

return

"2D shape"

   

}

}

class

Circle

:

Shape

{

    override

class

func description

(

)

String

{

       

return

"This is a circle"

   

}

}

print

(

MathHelper.

abs

(

35

)

)

print

(

Shape.

description

(

)

)

print

(

Circle.

description

(

)

)

print

(

Shape.

category

(

)

)

Running result:



35

这是一个形状

这是一个圆

二维图形

The key difference: type members defined with static cannot be overridden, while class can only be used in classes and allows subclasses to override with override.

Note:Stored type properties must be declared with static , whileclass is only for overridable computed type properties or type methods.


@discardableResult

If a method's return value is often ignored at call sites, you can add @discardableResult so the compiler does not warn when the return value is ignored.

Example

import Foundation

struct

BankAccount

{

    var balance

:

Int

   

// No warning when the return value is ignored

    @discardableResult

    mutating func deposit

(

_ amount

:

Int

)

Int

{

        balance

=

amount

       

return

balance

   

}

   

// Without @discardableResult, the compiler warns when the return value is ignored

    mutating func withdraw

(

_ amount

:

Int

)

Int

{

        balance

=

amount

       

return

balance

   

}

}

var account

=

BankAccount

(

balance

:

100

)

account.

deposit

(

50

)

let left

=

account.

withdraw

(

30

)

print

(

"Balance: (left)"

)

Running result:



余额:120

This attribute only suppresses the warning and does not change the method's actual behavior; the return value can still be used normally.


Common questions

The following problems occur most frequently when writing methods.

Error "argument labels do not match" when calling

Most likely a label is wrong. First check whether the parameter has an external label in the definition: if it is _, write nothing; if written as label name, write label; if nothing is written, use the parameter name itself.

Error when modifying a property in a struct method

An instance method cannot modify a value type's properties by default; add mutating to the method. If the instance is declared with let, change it to var as well.

Error when accessing an instance property in a type method

A type method has no instance context and cannot directly access instance properties. Either change the method to an instance method or make the data a type property as well.