Understanding
Introduction
In Swift, methods are functions that are associated with a
particular type, such as a class, structure, or enumeration. Methods
provide functionality to work with data encapsulated within these
types, allowing for code reuse and better organization.
Swift supports two types of methods:
- Instance Methods: These are methods that operate on instances of a type and have access to instance properties.
- Type Methods: These methods operate at the type level and do not require an instance.
Understanding how methods work in Swift is crucial for writing clean, efficient, and maintainable code.
Key Points to Remember
-
Methods are defined using the
func
keyword inside a class, structure, or enumeration. -
Instance methods have access to
self
, which represents the instance that is calling the method. -
Type methods use the
static
orclass
keyword to be associated with the type rather than an instance. - Methods can have parameters and return values like regular functions.
Syntax
Instance Method Syntax
class
ClassName {
func
methodName(parameterName: Type) ->
ReturnType {
// Method implementation
}
}
Type Method Syntax
class
ClassName {
static func
methodName(parameterName: Type) ->
ReturnType {
// Method implementation
}
}
Example 1: Defining and Calling an Instance Method
Let's define a simple method inside a class and call it on an instance.
class
Calculator {
func add(a: Int, b:
Int) -> Int {
return a +
b
}
}
let calc =
Calculator()
let sum =
calc.add(a: 5, b:
10)
print("Sum: \(sum)")
Output
Example 2: Using Self in an Instance Method
The self
keyword refers to the current instance of a
class.
class Person {
var name:
String
init(name:
String) {
self.name =
name
}
func greet() {
print("Hello, my name is \(self.name).")
}
}
let person =
Person(name:
"Alice")
person.greet()
Output
Example 3: Defining and Calling a Type Method
Type methods are associated with the type itself rather than an instance.
class
MathUtility {
static func
square(of
number: Int) ->
Int {
return number *
number
}
}
let
squaredNumber =
MathUtility.square(of: 4)
print("Square: \(squaredNumber)")
Output
Example 4: Mutating Methods in Structs
When modifying properties inside a method of a struct, use the
mutating
keyword.
struct Counter {
var value:
Int = 0
mutating func
increment() {
value += 1
}
}
var counter =
Counter()
counter.increment()
print("Counter Value: \(counter.value)")