An instance method in Swift is just a type method that takes the instance as an argument and returns a function which will then be applied to the instance.
class BankAccount {
var balance: Double = 0.0
func deposit(amount: Double) {
balance += amount
}
}
We can obviously create an instance of this class and call the deposit() method on that instance:
let account = BankAccount()
account.deposit(100) // balance is now 100
So far, so simple. But we can also do this:
let depositor = BankAccount.deposit
depositor(account)(100) // balance is now 200
Ole Begemann
class BankAccount {
var balance: Double = 0.0
func deposit(amount: Double) {
balance += amount
}
}
We can obviously create an instance of this class and call the deposit() method on that instance:
let account = BankAccount()
account.deposit(100) // balance is now 100
So far, so simple. But we can also do this:
let depositor = BankAccount.deposit
depositor(account)(100) // balance is now 200
Ole Begemann
Comments
Post a Comment