Member-only story

How to make extensions to Swift Optional Object ?

Understanding Swift Optional implementation

Prafulla Singh
1 min readAug 2, 2020

If you are looking for basic option usage, Please go here.

The Optional in swift is implement as enum with actual variable as temple enum parameter. The actual implementation of enum is here.

public enum Optional<Wrapped>: ExpressibleByNilLiteral {
case none
case some(Wrapped)
}
// implementation: https://github.com/apple/swift/blob/master/stdlib/public/core/Optional.swift

All the variable defined as optional(e.g. Int?, String? etc) are basically ‘Optional’ enum. As we know enum are extensible, we can extend to add more properties to it.

Extending Optional for All Object:

extension Swift.Optional {
var isNull: Bool {
switch self {
case .none:
return true
case
.some:
return false
}
}
}
////ORextension Swift.Optional {
var isNull: Bool {
return self == nil
}
}

Extending Optional for Specific Protocol type:

If we want Optional property only applicable to specific protocol like Collection(i.e. Arrays, Strings etc). We can attach condition to Wrapped object like following:

extension Swift.Optional where Wrapped: Collection {
var isNilOrBlank: Bool {
switch self {
case .none:
return true

--

--

Prafulla Singh
Prafulla Singh

No responses yet