Swift Methods
Swift methods are functions associated with specific types.
In Objective-C, classes are the only types that can define methods. However, in Swift, you can not only choose whether to define a class, struct, or enum but also define methods flexibly on the types (class, struct, enum) you create.
Instance Methods
In Swift, instance methods are methods that belong to instances of a particular class, struct, or enum.
Instance methods provide the following:
- Access to and modification of instance properties
- Functionality relevant to the instance's purpose
Instance methods are written within the curly braces ({}) of the type they belong to.
Instance methods can implicitly access all other instance methods and properties of their type.
Instance methods can only be called by a specific instance of their class.
Instance methods cannot be called without 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
}
}
// Initial count value is 0
let counter = Counter()
// Count value is now 1
counter.increment()
// Count value is now 6
counter.incrementBy(amount: 5)
print(counter.count)
// Count value is now 0
counter.reset()
print(counter.count)
The above program execution output is:
6
0
The Counter class defines three instance methods:
- increment increments the counter by 1;
- incrementBy(amount: Int) increments the counter by a specified integer value;
- reset resets the counter to 0.
The Counter class also declares a mutable property count to 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).
Swift methods are very similar to Objective-C methods. Like in Objective-C, the name of a Swift method typically uses a preposition to refer to the first parameter, such as with, for, by, etc.
Swift defaults to giving the first parameter name in a method a local parameter name and the second and subsequent parameter names global parameter names.
In the following example, 'no1' is declared as a local parameter name in Swift. 'no2' is declared globally and is accessible by external programs.
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 above program execution output is:
600
320
3666
Providing External Names
We can force an external name for the first parameter by using the local name as the external name (prior to Swift 2.0, this was done using the # symbol).
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
The self
property refers to the current instance of the class, struct, or enum. It is used to distinguish between instance properties and method parameters when they have the same name.
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 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("Inside self: \(res)")
}
func tot(c: Int) -> Int {
return res - c
}
func result() {
print("Result is: \(tot(c: 20))")
print("Result is: \(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:
Inside self: 900
Inside self: 1500
Result is: 880
Result is: 850
Result is: 1480
Result is: 1450
Modifying Value Types from Within Instance Methods
Structures and enumerations in Swift are value types. By default, the properties of a value type cannot be modified from within its instance methods.
However, if you need to modify the properties of a structure or enumeration within a particular method, you can opt to mutate that method. This allows the method to change its properties from within the method, and any changes made will persist after the method completes.
A method can also assign a new instance to its implicit self
property, and this new instance will replace the original instance after the method finishes.
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 a 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 that are called on an instance of a type. You can also define methods that are called on the type itself, known as type methods.
To declare type methods for structures and enumerations, prefix the method's func
keyword with the static
keyword. For classes, you can use the class
keyword to allow subclasses to override the method implementation.
Type methods are called with the dot syntax (.
).
import Cocoa
class Math
{
class func abs(number: Int) -> Int
{
if number < 0
{
return (-number)
}
else
{
return number
}
}
}
struct absno
{
var num: Int
init(num: Int) {
self.num = num
}
func absolutevalue() -> Int {
return Math.abs(number: num)
}
}
let a = absno(num: -35)
let b = absno(num: 35)
print(a.absolutevalue())
print(b.absolutevalue())
The output of the above program is:
35
35
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 program is:
35
5