μ-library enabling if/else and switch statements to be used as expressions.

Overview

swift-expression

Many languages such as Scala, Rust and Kotlin support using if/else and switch statements as expressions – meaning that they can by themselves return a value. Unfortunately, Swift is not one of these languages. Thankfully, Swift is powerful enough to let us express this at the μ-library level.

Initially, you would have to write this:

let number = 10

let fizzbuzz: String
switch (number % 3 == 0, number % 5 == 0) {
case (true, false):
    fizzbuzz = "Fizz"
case (false, true):
    fizzbuzz = "Buzz"
case (true, true):
    fizzbuzz = "FizzBuzz"
case (false, false):
    fizzbuzz = String(number)
}

This doesn't really feel like idiomatic Swift – we're not used to having uninitialized values floating around like this, and we need to remember to initialize the value on all paths.

This library enables you to use if/else and switch statements as expressions, which lets you "return" the value directly. This is what it looks like:

let number = 10

let fizzBuzz = expression {
    switch (number % 3 == 0, number % 5 == 0) {
    case (true, false):
        "Fizz"
    case (false, true):
        "Buzz"
    case (true, true):
        "FizzBuzz"
    case (false, false):
        String(number)
    }
}

Looks much better, doesn't it? And all we had to do is wrap it in a lightweight expression(_:) call.

What kind of sorcery is this?

No sorcery at all, actually! Implementing this took a grand total of 17 lines of code (including skipped lines). Do to this we use Result Builders, which essentially allow you to turn trees of statements and expressions into a single result.

You've probably already seen Result Builders in SwiftUI, and you'll see them soon in the Standard Library with the still-in-the-pipeline Pattern builder for parsing strings like regular expressions. Check out other interesting uses of Result Builders in the awesome-result-builders repository!

You might also like...
ZIP Foundation is a library to create, read and modify ZIP archive files.
ZIP Foundation is a library to create, read and modify ZIP archive files.

ZIP Foundation is a library to create, read and modify ZIP archive files. It is written in Swift and based on Apple's libcompression for high performa

Butterfly is a lightweight library for integrating bug-report and feedback features with shake-motion event.
Butterfly is a lightweight library for integrating bug-report and feedback features with shake-motion event.

Butterfly is a lightweight library for integrating bug-report and feedback features with shake-motion event. Goals of this project One of th

Focus is an Optics library for Swift (where Optics includes Lens, Prisms, and Isos)

Focus Focus is an Optics library for Swift (where Optics includes Lens, Prisms, and Isos) that is inspired by Haskell's Lens library. Introduction Foc

📘A library for isolated developing UI components and automatically taking snapshots of them.
📘A library for isolated developing UI components and automatically taking snapshots of them.

A library for isolated developing UI components and automatically taking snapshots of them. Playbook Playbook is a library that provides a sandbox for

A Swift micro library for generating Sunrise and Sunset times.

Solar A Swift helper for generating Sunrise and Sunset times. Solar performs its calculations locally using an algorithm from the United States Naval

Plugin and runtime library for using protobuf with Swift

Swift Protobuf Welcome to Swift Protobuf! Apple's Swift programming language is a perfect complement to Google's Protocol Buffer ("protobuf") serializ

A Swift package for rapid development using a collection of micro utility extensions for Standard Library, Foundation, and other native frameworks.
A Swift package for rapid development using a collection of micro utility extensions for Standard Library, Foundation, and other native frameworks.

ZamzamKit ZamzamKit is a Swift package for rapid development using a collection of micro utility extensions for Standard Library, Foundation, and othe

Hammer is a touch, stylus and keyboard synthesis library for emulating user interaction events
Hammer is a touch, stylus and keyboard synthesis library for emulating user interaction events

Hammer is a touch, stylus and keyboard synthesis library for emulating user interaction events. It enables better ways of triggering UI actions in unit tests, replicating a real world environment as much as possible.

Pigeon is a SwiftUI and UIKit library that relies on Combine to deal with asynchronous data.

Pigeon 🐦 Introduction Pigeon is a SwiftUI and UIKit library that relies on Combine to deal with asynchronous data. It is heavily inspired by React Qu

Owner
Nikita Mounier
Swift aficionado - currently developing Tap It
Nikita Mounier
`Republished` is a property wrapper enabling nested ObservableObjects in SwiftUI.

Republished The @Republished proprty wrapper allows an ObservableObject nested within another ObservableObject to naturally notify SwiftUI of changes.

Adam Zethraeus 13 Dec 5, 2022
Swift-when - Expression switch support in Swift

Swift When - supporting switch expressions in Swift! What is it? Basically, it a

Gordan Glavaš 7 Nov 24, 2022
iOS helper library that contains commonly used code in Uptech iOS projects

iOS helper library that contains commonly used code in Uptech iOS projects.

Uptech 1 Apr 1, 2022
MediaType is a library that can be used to create Media Types in a type-safe manner.

This is a general purpose Swift library for a concept of typed treatment for Media Types. We use this library on clients and servers to speak the same dialect and to enjoy all the comfort strong types provide over raw strings.

21Gram Consulting 79 Jul 19, 2022
A NEWS app which can be used to read,share and bookmark articles of various categories

Scoop A NEWS App for iOS 14 built using Swift which allow the users to read,bookmark and share news articles. Built using MVC architecture Requirement

Sai Balaji 3 Oct 12, 2022
A collection of common tools and commands used throughout the development process, customized for Kipple projects.

KippleTools A collection of common tools and commands used throughout the development process, customized for Kipple projects. ⚠️ The code in this lib

Kipple 10 Sep 2, 2022
The simplest way to display the librarie's licences used in your application.

Features • Usage • Translation • Customisation • Installation • License Display a screen with all licences used in your application can be painful to

Florian Gabach 51 Feb 28, 2022
This package will contain the standard encodings/decodings/hahsing used by the String Conversion Tool app.

This package will contain the standard encodings/decodings/hahsing used by the String Conversion Tool app. It will also, however, contain extra encoding/decoding methods (new encoding/decoding)

Gleb 0 Oct 16, 2021
A simple macOS utility that can be used to control the behaviour of Bose QC35 Headphones straight from the menu bar.

bose-macos-utility A simple macOS utility that can be used to control the behaviour of Bose QC35 Headphones straight from the menu bar. Why Have you e

Łukasz Zalewski 11 Aug 26, 2022
Cross-Platform, Protocol-Oriented Programming base library to complement the Swift Standard Library. (Pure Swift, Supports Linux)

SwiftFoundation Cross-Platform, Protocol-Oriented Programming base library to complement the Swift Standard Library. Goals Provide a cross-platform in

null 620 Oct 11, 2022