Programming in Swift: Functions & Types

Jan 4 2022 Swift 5.5, iOS 15, Xcode 13

Part 1: Functions

7. Functions as Parameters

Lesson Complete

Play Next Lesson
Next
Save for later
About this episode
See versions

See course reviews

See forum comments
Cinema mode Mark as Complete Download course materials
Previous episode: 6. Challenge: Overloads & Parameters Next episode: 8. Conclusion

Update Notes: This course was originally recorded in 2019. It has been reviewed and all content and materials updated as of October 2021.

Heads up... You've reached locked video content where the transcript will be shown as obfuscated text.

You can unlock the rest of this video course, and our entire catalogue of books and videos, with a kodeco.com Professional subscription.

Functions in Swift are simply another data type. You can assign them to variables and constants, and pass them into functions as arguments, just like you can any other type of value, like an Int or a String. Let’s see what that looks like in our Playground.

func add(number1: Int, number2: Int)  {

}
func add(number1: Int, number2: Int) -> Int {

}
  number1 + number2

var function = add
function(4, 2)
func subtract(_ a: Int, _ b: Int) -> Int {
  return a - b 
}
function = subtract
function(4, 2)
func printResult
func printResult(_ operate: 
func printResult(_ operate: 😺(Int, Int) -> Int
func printResult(_ operate: (Int, Int) -> Int, _ a: Int, _ b: Int) {}
  let result = operate(a, b)
  print(result)
printResult(add, 4, 2)
printResult(subtract, 4, 2)
printResult(+, 8, 13)
printResult(-, 8, 13)
printResult(*, 8, 13)
typealias Operate
typealias Operate = (Int, Int) -> Int
func printResult(_ operate: Operate, _ a: Int, _ b: Int) {