swift-for-python-programmers

Functions

🏡

Table of contents

  1. Definition
  2. Calling
  3. Overloading
  4. Closures

    4.1. Implicit return

    4.2. Shorthand

    4.3. Operator


1. Defining a function

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
}

2. Calling a function

let age = sayAge(age: 18)
print(age)

3. Function Overloading

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

4. Closures

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 } )

4.1 Implicit return method

var reversedNames = names.sorted(by: { s1, s2 in s1 > s2 } )

4.2 Shorthand method

var reversedNames = names.sorted(by: { $0 > $1 } )

4.3 Operator method

var reversedNames = names.sorted(by: >)