4.1. Implicit return
4.2. Shorthand
4.3. Operator
Functions are defined with the func
keyword in Swift, the parameters are annotated using :
func sayAge(age: Int8) -> String {
let myAge = String(format: "You are %d years old ", age)
return myAge
}
let age = sayAge(age: 18)
print(age)
Functions can be overloaded to accept parameters of different types, each having their own definition
func printInput(arg: Int) {
print("Input", arg)
}
func printInput(arg: String) {
print("Input", arg)
}
printInput(arg: 1)
Input 1
printInput(arg: "One")
Input One
Closures are like lambda
functions in Python
let names = ["Chris", "Alex", "Ewa", "Barry", "Daniella"]
func backward(_ s1: String, _ s2: String) -> Bool {
return s1 > s2
}
var reversedNames = names.sorted(by: backward)
This can also be written as
reversedNames = names.sorted(by: { (s1: String, s2: String) -> Bool in
return s1 > s2
})
Swift can infer the type from the context without being explicitly stated
var reversedNames = names.sorted(by: { s1, s2 in return s1 > s2 } )
var reversedNames = names.sorted(by: { s1, s2 in s1 > s2 } )
var reversedNames = names.sorted(by: { $0 > $1 } )
var reversedNames = names.sorted(by: >)