Swift-when - Expression switch support in Swift

Related tags

Utility swift-when
Overview

Swift When - supporting switch expressions in Swift!

What is it?

Basically, it allows you to (kinda) use switch statement as an expression - compare a value against a bunch of cases and return a single value based on the which case passes.

This functionality exists in most popular languages as it leads to more elegant and concise code (e.g, C#, Java, Kotlin). Consider this example:

public enum Colors: WhenCompliant {
  case red, blue, green
  
  var hexString: String {
    when(self) { // isn't this nice?
      Colors.red => "#FF0000"
      Colors.green => "#00F000"
      Colors.blue => "#0000FF"
    }
  }
}

OK, but why?

Because I wrote something like this way too many times:

public enum Colors: WhenCompliant {
  case red, blue, green
  
  var hexString: String {
    switch self { // :(
      case Colors.red:
        return "#FF0000"
      case Colors.green:
        return "#00F000"
      case Colors.blue:
        return "#0000FF"
    }
  }
}

Writing out a full switch to transform a single enum value into something else, alongside all the cases, colons and explicit returns is unnecessarily verbose and ceremonial.

The same is true for a bunch of if-else if-...-else that all return the same value:

func describeNumber(_ n: Int) -> String {
  if n > 0 {
    return "positive"
  } else if n < 0 {
    return "negative"
  } else {
    return "zero"
  }
}

This package aims to solve those issues.

What it can do

Use with enums

To use an enum with when, it needs to be WhenCompliant, which implies being Hashable and CaseIterable:

enum Colors: WhenCompliant {
  case red, blue, green
}

After that, things get really simple:

func describeColor(_ color: Colors) {
  let description = when(color) {
    Colors.red => "red"
    Colors.blue => "blue"
    Colors.green => "green"
  }
  print(description)
}

When called, when checks if all enum cases are taken care of. If not, a runtime error is thrown.

Alternatively, you can specify the default clause:

func describeColor(_ color: Colors) {
  let description = when(color) {
    Colors.red => "red"
    Colors.blue => "blue"
    "other" // the default clause
  }
  print(description)
}

If multiple cases should map to the same result, wrap them in an array:

func describeColor(_ color: Colors) {
  let description = when(color) {
    [Colors.red, Colors.blue] => "redOrBlue"
    Colors.green => "green"
  }
  print(description)
}

Use with boolean expressions

Alternatively, when can be used as a generic shorthand for a bunch of if-else if-...-else statements that all return the same value. Check out this example:

func describeNumber(_ n: Int) -> String {
  when {
    (n > 0) => "positive"
    (n < 0) => "negative"
    "zero" // default clause
  }!
}

What it can't do

  • when can't work with enums that have associated values. Consequently, it also can't unwrap associated values (i.e, no case let).
  • switch offers compile-time guarantee that all cases are covered. when does that at runtime.

Installation

This component is distrubuted as a Swift package. Just add this URL to your package list:

https://github.com/globulus/swift-when

Changelog

  • 1.0.0 - Initial release.
You might also like...
Swift-DocC is a documentation compiler for Swift frameworks and packages aimed at making it easy to write and publish great developer documentation.

Swift-DocC is a documentation compiler for Swift frameworks and packages aimed at making it easy to write and publish great developer docum

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

Swift - ✏️Swift 공부 저장소✏️

Swift 스위프트의 기초 1. Swift의 기본 2. 변수와 상수 [3. 데이터 타입 기본] [4. 데이터 타입 고급] 5. 연산자 6. 흐름 제어 7. 함수 8. 옵셔널 객체지향 프로그래밍과 스위프트 9. 구조체와 클래스 10. 프로퍼티와 메서드 11. 인스턴스 생

Swift-ndi - Swift wrapper around NewTek's NDI SDK

swift-ndi Swift wrapper around NewTek's NDI SDK. Make sure you extracted latest

__.swift is a port of Underscore.js to Swift.

__.swift Now, __.swift is version 0.2.0! With the chain of methods, __.swift became more flexible and extensible. Documentation: http://lotz84.github.

SNTabBarDemo-Swift - Cool TabBar With Swift
SNTabBarDemo-Swift - Cool TabBar With Swift

SNTabBarDemo-Swift Cool TabBar How To Use // MARK: - setup private func setu

Swift-compute-runtime - Swift runtime for Fastly Compute@Edge

swift-compute-runtime Swift runtime for Fastly Compute@Edge Getting Started Crea

Swift-HorizontalPickerView - Customizable horizontal picker view component written in Swift for UIKit/iOS

Horizontal Picker View Customizable horizontal picker view component written in

swift-highlight a pure-Swift data structure library designed for server applications that need to store a lot of styled text

swift-highlight is a pure-Swift data structure library designed for server applications that need to store a lot of styled text. The Highlight module is memory-efficient and uses slab allocations and small-string optimizations to pack large amounts of styled text into a small amount of memory, while still supporting efficient traversal through the Sequence protocol.

Owner
Gordan Glavaš
Gordan Glavaš
BCSwiftTor - Opinionated pure Swift controller for Tor, including full support for Swift 5.5 and Swift Concurrency

BCSwiftTor Opinionated pure Swift controller for Tor, including full support for

Blockchain Commons, LLC — A “not-for-profit” benefit corporation 4 Oct 6, 2022
Mechanical editing support for Package.swift manifests

Mechanical editing support for Package.swift manifests. Implements Swift Evolution proposal SE-301

Owen Voorhees 9 Jan 4, 2023
This is a Swift package with support for macOS that allows to start Java Jar's with the default or a custom JVM.

Jar.swift jar runner for macos Jar.swift is created and maintaned with ❥ by Sascha Muellner. What? This is a Swift package with support for macOS that

Swift Package Repository 1 Nov 11, 2021
Swift Sequences are limited in that they don't support Iterators with a throwing next().

FailableSequence Swift Sequences are limited in that they don't support Iterators with a throwing next(). There are several use cases for such sequenc

Berik Visschers 0 Dec 6, 2021
Support library of BudouX.swift to handle HTML

HTMLBudouX.swift HTMLBudouX.swift is a support library of BudouX.swift to handle HTML. Detail about BudouX.swift is here Usage You can translate an HT

griffin-stewie 1 Dec 31, 2021
Collection of native Swift extensions to boost your development. Support tvOS and watchOS.

SparrowKit Collection of native Swift extensions to boost your development. Support iOS, tvOS and watchOS. If you like the project, don't forget to pu

Ivan Vorobei 119 Dec 20, 2022
macOS utility for converting fat-frameworks to SPM-compatible XCFramework with arm64-simulator support

xcframework-maker macOS utility for converting fat-frameworks to SPM-compatible XCFramework with arm64-simulator support. ?? Description make-xcframew

Dariusz Rybicki 312 Dec 22, 2022
Proper YAML support for Objective-C. Based on recommended libyaml.

YAML.framework for Objective-C Based on C LibYAML library (http://pyyaml.org/wiki/LibYAML) by Kirill Simonov. YAML.framework provides support for YAML

Mirek Rusin 236 Aug 29, 2022
A drop-in `NSComboButton` replacement with pre macOS 13 support.

DSFComboButton A drop-in NSComboButton replacement control with pre macOS 13 support. For when you want to adopt NSComboButton but have to maintain co

Darren Ford 8 Nov 9, 2022
Swift Markdown is a Swift package for parsing, building, editing, and analyzing Markdown documents.

Swift Markdown is a Swift package for parsing, building, editing, and analyzing Markdown documents.

Apple 2k Dec 28, 2022