Do You Truly Understand the Distinction Between Swift Functions and Methods?
In Swift, both functions and methods are used to define blocks of code that perform a specific task. However, there is a subtle difference between the two.
Function:
Example of a function:
func greet(name: String) -> String {
return "Hello, \(name)!"
}
Method:
Example of an instance method:
class MyClass {
func printMessage() {
print("This is an instance method.")
}
}
let myInstance = MyClass()
myInstance.printMessage()
Example of a type method:
class MyClass {
class func printStaticMessage() {
print("This is a type method.")
}
}
MyClass.printStaticMessage()
All methods are functions, but not all functions are methods.
In summary, the key distinction is that a function is a standalone block of code, while a method is a function associated with a specific type and can be called on instances of that type.