avatarSteven Curtis

Summary

This webpage provides a tutorial on re-implementing optionals in Swift, using enums and associated values, with examples for Integer and generic types.

Abstract

The webpage titled "Re-implement optionals in Swift" discusses the concept of optionals in Swift and how they can be re-implemented using enums and associated values. The article begins by explaining the prerequisites for understanding the topic, such as basic knowledge of Enum and associated values. It then delves into the terminology, defining optionals and enums. The author proceeds to demonstrate the official version of Integer optionals in Swift and then shows how to implement Integer optionals using enums. The article also covers instantiating nil and implementing generic optionals. The author provides code examples throughout the tutorial, and the full Swift file is available on GitHub.

Bullet points

  • Optionals in Swift are a type that handles the absence of a value.
  • Optionals can be implemented using enums with associated values.
  • The official version of Integer optionals in Swift is demonstrated.
  • Integer optionals can be implemented using enums and associated values.
  • Nil can be instantiated using the provided code example.
  • Generic optionals can be implemented using Swift generics.
  • The full Swift file for the tutorial is available on GitHub.

Re-implement optionals in Swift

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:

Swift
Recommended from ReadMedium