Hamdouchi Interactive
  • Welcome
  • Mobile
  • Tech Blog
    • Swift
    • SwiftUI
  • Let's Talk

Unlocking the Power of Swift:
A Tech Blog Series

Welcome to our tech blog series dedicated to exploring the world of Swift and its related topics. Our goal is to provide valuable insights and in-depth analysis on the latest advancements in the Swift programming language, including design patterns and data structures. Stay tuned for our upcoming articles and join the discussion on the exciting world of Swift programming!

Explore all Swift Topics

Handling Default Cases in Swift Enums

10/29/2023

0 Comments

 
Picture
​Swift enums are a versatile tool for creating custom data types with a finite set of related values. However, sometimes you encounter situations where you need to deal with input values that don't perfectly match any of the defined cases. This is where the concept of default cases becomes invaluable. In this blog, we'll explore how to implement default cases in Swift enums using protocols and extensions, with a practical example.

    
​Let's break down the code step by step to understand how it works and why it's useful.

​DefaultCase Protocol:

The DefaultCase protocol is defined as a protocol with two requirements:
  1. It must conform to the RawRepresentable protocol, indicating that it is associated with a raw value type (usually an integer or string).
  2. It must provide a static property called defaultCase of type Self. Here, Self represents the enum type conforming to this protocol.

​DefaultCase Extension:

  • An extension is provided for types that conform to the DefaultCase protocol.
  • Inside this extension, there's a static function called create(with value: RawValue?). This function accepts an optional RawValue parameter, which represents the raw value of the enum case you want to create.

​Implementation of create(with value: RawValue?):

  • This function starts with a guard statement to handle scenarios where the RawValue is nil. If it’s nil, the function returns the defaultCase associated with the enum. This ensures that when you can’t create a valid enum case from the provided raw value, you get a reasonable default case instead.
  • If the raw value is not nil, the function attempts to create an enum case using the Self(rawValue: rawValue) initializer. This initializer is automatically generated by Swift because our protocol conforms to RawRepresentable.
  • If the creation of the enum case succeeds, the function returns the created case. Otherwise, it falls back to returning the defaultCase.

​Usage Example: DistanceUnit

​Now, let's see how you can use this code to simplify working with enums. We'll use the DistanceUnit enum as an example:

    
In this example, we have the DistanceUnit enum, which conforms to the DefaultCase protocol. We've also provided a default case, .imperial. When creating enum cases based on user preferences or other input, the create(with:) function ensures that you always receive a valid enum case or the default case if the raw value doesn't match any defined cases.

​The provided code snippet illustrates a practical approach to implement default cases in Swift enums. This technique is invaluable for handling scenarios where input values may not align perfectly with enum cases. By adopting the DefaultCase protocol and the create(with:) function, you can streamline enum handling, improve code robustness, and gracefully handle unexpected input. This strategy enhances the maintainability and reliability of your Swift code, making it a valuable addition to your programming toolkit.
0 Comments
    Picture

    Mohamed Hamdouchi


    Author

    Lead iOS Engineer.
    I help develop Design System Libraries.
    Creative Thinker.
    Featured on the App Store with 4M+ downloads.


    Archives

    November 2023
    October 2023
    August 2023
    July 2023
    June 2023
    May 2023
    April 2023
    March 2023
    February 2023
    January 2023
    December 2022


    Categories

    All
    Abstract Factory
    Animation
    Array
    Associatetype
    Avl
    Behavioral
    Bridge
    Builder
    Case
    Chaining
    Chain Of Responsibility
    Class
    Closure
    Coalescing
    Coercion
    Command
    Composite
    Computed Property
    Conditional Conformance
    Crash
    Creational
    Data Structure
    Decorator
    Default Case
    Design Pattern
    Dictionary
    Enum
    Extension
    Facade
    Factory
    Factory Method
    Flyweight
    Function
    Generics
    Graphs
    Guard
    Hash Table
    Heap
    Initialization
    Interpreter
    Ios
    Iterator
    Linked List
    Lowercase
    Mapping
    Mediator
    Memento
    Observer
    Optional
    Pattern Matching
    Protocol
    Prototype
    Proxy
    Quadratic Probing
    Queue
    Search
    Self
    Sequence
    Singleton
    Stack
    State
    Strategy
    Strikethrough
    Struct
    Structural
    Subscript
    Swift
    Template Method
    Text
    Tree
    Tries
    Try
    UIKit
    Uilabel
    UITableView
    Uppercase
    Visitior

​​COPYRIGHT © 2009 HAMDOUCHI INTERACTIVE, LLC. ​ALL RIGHTS RESERVED
  • Welcome
  • Mobile
  • Tech Blog
    • Swift
    • SwiftUI
  • Let's Talk