Swift: Functions

Swift: Functions

Learn from scratch about functions, and functional programming.

What is a function? A function is a block of code that performs a specific task. Functions allow us to divide our program into modular chunks, so that each function performs one action. This makes code more organized and reusable.

Why use functions? There are several reasons to use functions:

  • Modularity: Functions group instructions that perform a specific task, keeping related code together.

  • Reusability: The same function can be called multiple times, at different places in the program. This reduces repetition.

  • Readability: Functions give our code a structure, making it easier to read and understand.

  • Maintainability: If a bug is found or a change is needed, we fix it in one place (the function) and it affects the whole program.

How are functions implemented in Swift? In Swift, functions are defined using the func keyword:

func functionName(parameterName: ParameterType) -> ReturnType {
    // function body
}

For example:

func square(number: Int) -> Int {
    return number * number  
}

This function takes an integer as input and returns its square. We call functions like this:

let result = square(number: 5)
print(result) // Prints 25

We can also define functions without return values:

func printMessage() {
    print("Hello!")
}

printMessage() // Prints Hello!

Programming paradigm Functions are an example of the procedural programming paradigm. This involves breaking down a program into simple steps (functions), which are called in a defined order to perform some computation.


Functional Programming

F.P. Swift is not a purely functional programming language, but it does support some functional programming concepts and features:

  • First-class functions: Functions in Swift are first-class citizens, meaning they can be passed as arguments to other functions, returned from functions, and assigned to variables. This allows functions to be manipulated as any other object.

  • Closures: Swift supports closures, which are self-contained blocks of code that can be passed around and used in functions. Closures capture their surrounding context and allow access to variables from that context.

  • Immutability by default: Variables and constants in Swift are immutable by default. Functions that do not modify their parameters can be considered "pure functions", a key concept in functional programming.

  • Higher-order functions: Swift has many built-in functions that take other functions as arguments, like map, filter and reduce. This is a common trait of functional languages.

However, Swift is not a purely functional language because:

  • It supports mutability through variables declared with var.

  • Functions can have side effects by modifying variables outside their scope.

  • It supports object-oriented programming features like classes, inheritance, and methods.

So in summary, while Swift supports some functional programming concepts, it is primarily an object-oriented programming language that also incorporates functional programming where useful. The functional features allow for more concise and declarative code in some situations.


Recursive Functions

Recursive functions in Swift are functions that call themselves. This allows solving problems by breaking them down into smaller subproblems until reaching a base case.

Here's an example of a recursive function in Swift to calculate the factorial of a number:

func factorial(number: Int) -> Int {
    if number == 1 {
        return 1
    } else {
        return number * factorial(number: number - 1) 
    }
}

We break down the problem as follows:

  • Base case: If the number is 1, the factorial is 1. This stops the recursion.

  • Recursive case: Otherwise, multiply the number by the factorial of one less than that number. This keeps calling the function recursively until it reaches the base case.

Another example is a function to sum the digits of an integer:

func sumDigits(_ number: Int) -> Int {
    if number < 10 {
        return number 
    } else {
        let remainder = number % 10
        let quotient = number / 10
        return remainder + sumDigits(quotient)
    }
}

Here the base case is when the number is less than 10, and the recursive case keeps dividing the number by 10 and adding the remainder to the sum of the digits of the quotient.

The key things to remember about recursive functions are:

  • Have a base case to stop the recursion

  • Make progress towards the base case in the recursive case

  • Avoid infinite recursion (the base case must eventually be reached)

Hope this explanation of recursive functions in Swift helps! Let me know if you have any other questions.


Swift Features

Swift's core functions and libraries provide the essential building blocks for writing Swift code. Some of the most important core features are:

  • Collections: Arrays, Sets, Dictionaries - Swift has powerful collections that are easy and safe to use.

  • Strings and Characters: Swift strings are built-in types that provide many useful functions.

  • Control Flow: if/else, for/in, while, guard - Swift's control flow statements are very powerful and safe.

  • Functions: First-class functions, closures, recursion - Functions are a central part of Swift's syntax.

  • Classes and Structures: Swift has both class and struct types to organize your code.

  • Enumerations: Enums allow you to define a finite set of related values.

  • Operators: Swift has familiar operators like + - * / and also custom operators.

  • Error Handling: do/catch/throw - Swift has a robust error handling system.

  • Optionals: Optionals indicate that a value may be absent. They handle nil gracefully.

  • Generics: You can write code that works with any type, not just a specific one.

  • Protocols: Protocols define a blueprint of methods, properties, etc that types can conform to.

  • C and Objective-C Interoperability: Swift can interface with C and Objective-C libraries.

All of these core features and more are provided by Swift's standard library. Some other useful libraries include:

  • Foundation: Provides data types for strings, numbers, dates, files, etc.

  • UIKit: For building iOS apps with views, controls, layout, animations, etc.

  • SpriteKit: For creating 2D games for iOS, tvOS and macOS.

  • GameplayKit: Framework for AI, physics, simulation and other game technologies.

So in summary, Swift's core features and libraries provide all the essential functionality needed to build applications in Swift, from the lowest-level syntax and data types to high-level frameworks for building specific kinds of apps.


Disclaim: I have not asked yet all the questions. I'm using Rix (and AI bot) to learn Swift. Soon I will be able to create new examples of my own and use Swift for my next apps. You can read more in next article.