Re-implement optionals in Swift

Image for post
Image for post

In Swift optionals are implemented as enums that contain some or none.

Prerequisites:

  • Some basic understanding of Enum and associated values

Terminology

Optionals: Swift introduced optionals that handle the absence of a value, simply by declaring if there is a value or not. An optional is a type on it’s own!

enum: An enumerated type is a data type consisting a set of members of the type.

The official version of Integer optionals

The idea here is that we will try to implement optionals much how it is performed in Swift.

So in Swift we can create optional Ints with the following:

Implementing Integer optionals in Swift

So optionals can be implemented through an enum (with associated value).

Calling it “Optional” when there is no value is not ideal, but matches the internal implementation.

You can also instantiate nil with:

let optionalInt : MyIntOptional = .Nil

It is trivial to do the same with String, or Character. However, what would be better is to use Generics to produce a generic optional

Implementing generic optionals in Swift

Generic implementations in Swift are not usually problematic, and luckily here it isn’t either:

A Swift file is published on GitHub: https://github.com/stevencurtis/implementoptionals/blob/master/main.swift

Want to get in contact? Try the link here:

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store