Swift Methods with Examples
Interactive Online Courses: Elevate Skills & Succeed Enroll Now!
Methods play an important role in object-oriented programming. Swift Methods are functions defined with a particular type like class, structures or enumerations. It defines their behaviour. They encapsulate operations that objects can perform. The syntax of methods is similar to functions in Swift.
func methodName(parameters) -> returnType{
//code statements
Return statement
}In this article, we’ll discuss different kinds of methods. We’ll also know about unique concepts related to it with the help of relevant examples.
Instance Methods in Swift
Swift Instance methods are the methods that are associated with an instance of a type. We can access and modify its properties. We can perform operations in that instance.
For example,
class Company{
var name: String
init(name: String){
self.name = name
}
func greet(){
print("Hello from \(name)!")
}
}
let company1 = Company(name: "DataFlair")
print(company1.name)Output:
DataFlair
Here, the methods init() and greet() are the instance methods.
Static or Type Methods in Swift
Swift Type Methods are the methods that are associated with the type itself. We use the static keyword for structures and enums and class keywords for classes. These are useful when we perform operations that are not specific to the instance. These are useful when we don’t need to create an instance.
For example,
struct SquaredValue{
static func square(num: Int) -> Int {
return num * num
}
}
let answer = SquaredValue.square(num: 6)
print(answer)Output:
36
Local & External Parameter Values in Swift
In Swift, the characteristics of local and global parameter names are different for functions and methods. Usually, the first parameter of a method has with, for or by prepositions. We treat the first parameter name in a method as a local parameter name. The parameter names other than the first parameter name are treated as a global parameter name. This means that these global parameter names can be accessed from anywhere in our program.
For example,
class Addition{
var sum: Int = 0
func add(num1: Int, num2: Int){
sum = num1 + num2
print(sum)
}
}
let example = Addition()
example.add(num1: 3,num2: 4)
example.add(num1: 7,num2: 90)
example.add(num1: 32,num2: 45)Output:
7
97
77
Here, the local parameter name is num1, and the global parameter name is num2.
Global Parameter Names using # and _ symbol
Swift provides a way to change the local parameter names into global parameter declarations. We do this by prefixing the ‘#’ symbol with the first parameter name. This makes the first parameter accessible globally.
If we need to access the subsequent parameter names with an external name, we can override the method names with the ‘_’ symbol.
Swift Self Properties in Methods
We use self-property to refer to a current instance of a class or structure in its own methods. It is an implicit property of every instance of a type. These help to distinguish between instance properties and method parameters sharing the same name. For example,
class Company{
var name: String
init(name: String){
self.name = name
}
func greet(){
print("Hello from \(self.name)!")
}
}Here, we use the self property to access the instance’s name property within the init() and greet() methods.
Mutating Methods in Swift
In Swift, we cannot change the values of properties belonging to the value types, such as structures and enumerations. But Swift provides us a way to modify these values with the help of the mutating keyword. We can place the mutating keyword.
struct Temperature{
var exampleTemp: Double
mutating func toFahrenheit(){
exampleTemp = (exampleTemp * 9.0 / 5.0) + 32.0
}
}
var presentTemp = Temperature(exampleTemp: 28)
print("Temperature in Celsius: \(presentTemp.exampleTemp)")
presentTemp.toFahrenheit()
print("Temperature in Fahrenheit: \(presentTemp.exampleTemp)")Output:
Temperature in Celsius: 28.0
Temperature in Fahrenheit: 82.4
Self Property for Mutating Methods
The self-property in mutating methods refers to the current instance. We use it to access or modify its instance properties. For example,
struct SimpleCounter {
var count = 6
mutating func increment() {
self.count += 1 // Using 'self' to access and modify the 'count' property.
}
}
var counter = SimpleCounter()
counter.increment()
print(counter.count)Output:
7
Conclusion
Swift Methods are similar to functions, but we define them for a particular type. In this article, we have covered different kinds of methods in Swift, like static and instance methods. We’ve understood the usage of self-property. We have gone through mutating methods and other concepts related to methods in Swift.
Did we exceed your expectations?
If Yes, share your valuable feedback on Google

