In Swift optionals are implemented as enums that contain some or none.
- Some basic understanding of Enum and associated values
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: