🦺 Making your own custom Optional 👌

December 2, 2024

Welcome to the issue #24 of the iOS Coffee Break Newsletter 📬.

Swift's Optional type ensures safer code by clearly managing values that may or may not exist! While Swift natively supports Optionals with (?), some libraries or frameworks lack this syntax.

A common iOS interview question is: How can you create a custom Optional?

Here is a quick implementation:

// MARK: - Optional is an enum with two cases: some value and none (nil)
enum CustomOptional<T> {
    case some(T)
    case none
 
    var value: T? {
        switch self {
        case .some(let value):
            return value
        case .none:
            return nil
        }
    }
 
    func unwrapped() throws -> T {
        switch self {
        case .some(let value):
            return value
        case .none:
            throw CustomOptionalError.valueIsNil
        }
    }
 
    // MARK: - Custom Optional Error enum
    enum CustomOptionalError: Error {
        case valueIsNil
    }
}
 
// MARK: - Initializing the value
let customOptionalString: CustomOptional<String> = .some("hello world!")
do {
    let value = try customOptionalString.unwrapped()
    print("Custom optional string value unwrapped: \(value)")
} catch {
    print(error)
}
 
let customOptionalIntNoValue: CustomOptional<Int> = .none
do {
    let value = try customOptionalIntNoValue.unwrapped()
    print("Custom optional int value unwrapped: \(value)")
} catch {
    print(error)
}

Here is the console output:

Mastering optionals is key to writing reliable Swift code. Creating custom optional types helps understand their structure and allows extension for specific needs. Whether preparing for interviews or deepening knowledge of Swift, becoming proficient in optionals strengthens your skills as an iOS developer 💪!

Now it is time to dive into some iOS development topics submitted by the community. Here are this week's highlighted resources. Hope you enjoy 🙌.

👅 Working with Natural Language framework

Part 2 of Artem's SwiftUI text editing series dives into the Natural Language framework, showcasing its real time text analysis capabilities.

I am surprised this framework isn't used more often. It is a powerful tool for text analysis — free, fast, and fully functional offline!

🧰 Mastering Swift for Scripting & Tooling

Natan's Swift Connection 2024 talk is now available, and it is one I have been eagerly anticipating! I have been following Natan's work for a while, and I am a big fan of his clear, engaging teaching style!

If you are interested in scripting, tooling, or deepening your Swift expertise, this is a must-watch talk!

🤦‍♂️ Static, Dynamic, Mergeable, oh, my!

How do static and dynamic linking impact build times?

If this concept feels unclear, I recommend checking out Jacob's insightful explanation to clarify the differences and their effects on your builds! It is definitely worth a read!

✌️ Storing two types in the same variable using Either

Vincent shared a clever tutorial on refactoring code to handle mixed data types using a generic Either enum. This enum supports two generic types, with each case storing an associated value of one type. It is a versatile approach, similar to Swift's Result type.

Is it just me, or are enums amazing?