Swift Methods

In swift, Properties are the attributes of specific name type but methods are the behaviors which extend its functionality. In swift, Methods are similar to functions that are associated with a special type.

 

In swift, we have two types of methods available those are

 

  • Instance Methods
  • Type Methods

We can easily define an instance method at structures, classes, and enumeration which enclosed a specific task and functionality with their instances. We can access the value of the method by creating the instance of the method.

 

Same way we can define type method in structuresclasses and enumerations, which are associated with the type itself.

Syntax of Swift Methods

Following is the general form of methods declaration. Method declaration is similar to function declaration in a swift programming language.

 

func funcname(Parameters: Datatype) -> returntype {

//Varibales,Methods Declaration here

return parameters

}

If you observe above syntax we defined methods same as functions. To know more about functions check this Swift Functions.

 

Once we declare a method we need to create an instance of method and assign the same to a variable then we can access all the properties which are located inside of the method. Following is the general way to create an instance of the method.

 

var methodInstance = funcname()

Now we will see how to declare and use functions in swift programming language with example. 

Swift Method Example

Following is the simple example of defining methods in a swift programming language.

 

func hellomsg(msg: String) -> String {

return msg

}

var methodInstance = hellomsg(msg:"Welcome to Tutlane")

print(methodInstance)

If you observe above example we defined a method and created an instance, assigned to a variable.

 

When we run the above program in swift playground we will get a result like as shown below

 

Welcome to Tutlane

This is how we can create methods in a swift programming language based on our requirements.

Swift Instance Methods

Instance methods are the functions that are associated with a particular class, enumeration or structures. These instance methods will provide the functionality to access its properties and methods directly.

 

In swift programming language, the syntax of instance methods will be same as functions. For more details about functions check this Swift Functions.

 

Methods are similar to instance methods but in which we can create the instance of our class then using dot (.) syntax we can call the specific function or method based on our requirements. 

 

Now we will see how to create instance methods in a swift programming language with examples.

Swift Instance Method Example

Following is the example of creating and accessing methods from the class instance.

 

class Student {

var name = ""

func studentname(str: String) {

name += str

print(name)

}

}

var info = Student()

info.studentname(str: "Suresh")

info.studentname(str: " Dasari")

If you observe above example we created a class “Student” with one property, function / method and accessing the class method by creating an instance “info” for the class “Student”.

 

When we run the above example in swift playground we will get a result like as shown below.

 

Suresh

Suresh Dasari

This is how we can use instance methods in the swift programming language to access class properties or methods based on our requirements.

Swift Self-Property in Methods

In swift, self is a special keyword that is used to refer the current instance of its own instance methods and we can access the properties of a current instance with its name type by using self-keyword.

 

In Swift, every instance has its own type called self-property. Now we will see how to use self-property in a swift programming language with example.

 

Following is the example of adding two numbers in which self refers to the properties or methods of the current instance.

 

class addition {

let num1: Int

let num2: Int

let result: Int

init(no1: Int, no2: Int) {

self.num1 = no1

self.num2 = no2

result = no1 + no2

}

}

let pri = addition(no1: 3454, no2: 454)

print(pri.result)

If you observe above example we are using self to refer properties or methods of current instance and we are using self to distinguish between parameter name and the property name.

 

When we run the above program in swift playground we will get a result like as shown below

 

3908

This is how we can use self-property in a swift programming language to refer properties or methods of current instance based on our requirements.

Swift Modify Value Types from Instance Methods

In swift structures and enumerations are referred as a value types and the properties of value types cannot be modified from its instance methods. 

 

In case if we want to modify the properties of value types (structure or enumeration) in a method, Swift provides us the keyword called mutating which will mutate the method properties and the changes whatever we do to the properties will be written back to the original structure or enumeration whenever the method ends.

 

Now we will see how to modify value types in methods with examples in swift programming language.

 

Following is the example of modifying value type properties using a mutating keyword in the swift programming language.

 

struct ValType {

var num = 50

mutating func calculate() -> Int {

num = num+20

return num

}

}

var insval = ValType()

print(insval.calculate())

If you observe above example we are updating structure property values in calculate function using mutating keyword. 

 

When we run the above program in swift playground we will get a result like as shown below

 

11

Following is another example of modifying value type properties in methods by using the mutating keyword.

 

struct SampleStruct {

var num = 43

func normFunc(z:Int) -> Int {

return self.num+56+z

}

mutating func mutFunc(x:Int)->Int{

num=num+456

return num+x

}

func sampleFunc() -> Int {

return num+34

}

}

var insfn = SampleStruct()

print(insfn.normFunc(z:45) )

print(insfn.mutFunc(x:344) )

print(insfn.sampleFunc())

print(insfn.num)

var exin = SampleStruct()

print(exin.num)

When we execute above example in swift playground we will get result like as shown below

 

144

843

533

499

43

Swift Self Property for Mutating Method

In swift mutating methods, we can assign a new instance to the self property. Following is the example of using self property in swift mutating methods.

 

enum Animals {

case Cat, Dog, Elephant

mutating func Types() {

switch self {

case .Cat:

self = .Dog

case .Dog:

self = .Elephant

case .Elephant:

self = .Cat

}

}

}

var insInfo = Animals.Cat

insInfo.Types()

print(insInfo)

insInfo.Types()

print(insInfo)

If you observe above example we are assigning new instance to the properties in mutating methods using self property.

 

When we run above program in swift playground we will get a result like as shown below

 

Dog

Elephant

This is how we can assign the new instance to self properties in mutating methods based on our requirements in swift programming language.

Swift Type Methods

Generally, in swift instance methods will call whenever we create an instance of particular type same way we can create methods that are called on the type itself, these methods are called type methods.

 

In classes, we can represent type methods by using func keyword and in structures and enumerations we can define type methods by using static keyword before the methods func keyword.

 

In swift, we can call and access type methods by using dot (.) syntax like instance methods. However, we can call type methods on the type, not on the instance of type.

 

Now we will see how to use type methods in a swift programming language with examples. 

 

Following is the example of defining and using type methods in a swift programming language.

 

class Sample {

classfunc addition(num:Int)->Int {

return (10 + num)

}

}

struct Calculate {

staticfunc multiplication(num:Int)->Int {

return (10 * num)

}

}

let addval = Sample.addition(num:90)

let prodval = Calculate.multiplication(num:5)

print(addval)

print(prodval)

 

If you observe the above example we defined type methods in classes and structures and accessing type methods just by using type. To define type methods in classes we used func keyword just before the method and in structures we used static keyword just before the methods func keyword.

 

When we run the above example in swift playground we will get a result like as shown below.

 

100

50

This is how we can use type methods in a swift programming language to access methods using the type of methods based on our requirements.