This page has moved to swiftly.dev/functions! The archive below will not be updated.
Functions are a special type of closures. Functions are first-class types, so a function can be passed in as a parameter to another function. Also, a function can return another function.
() -> ()
(String) -> ()
(Int, Int) -> (Int)
() -> ()
This function takes no parameters, and returns nothing.
func greet() {
print("Hello")
}
greet()
// Output: "Hello"
(String) -> ()
This function takes one parameter, a String
, and returns nothing.
func greet(person: String) {
print("Hello \(person)")
}
greet(person: "Aliya")
// Output: "Hello Aliya"
(Int, Int) -> (Int)
This function takes two parameters, both Ints
, and returns an Int
.
func multiply(x: Int, y: Int) -> Int {
return x * y
}
print(multiply(x: 5, y: 6))
// Output: "30"
This function takes two parameters, both Ints
, and returns an Int
.
func greet(person: String = "guest") {
print("Hello \(person)")
}
greet()
greet(person: "Aliya")
// Output:
// Hello guest
// Hello Aliya
The function perform
has type ((Int, Int) -> Int, Int, Int) -> Int
.
func multiply(x: Int, y: Int) -> Int {
return x * y
}
func perform(fn: (Int, Int) -> Int,
a: Int,
b: Int) -> Int {
return function(a, b)
}
let result = perform(fn: multiply,
a: 5,
b: 6)
print(result)
// Output: "30"
The function operation
has type () -> (Int, Int) -> Int
.
func multiply(x: Int, y: Int) -> Int {
return x * y
}
func operation() -> ((Int, Int) -> Int) {
return multiply
}
let myOperation = operation()
let result = myOperation(5, 6)
print(result)
// Output: "30"