concept Optional in category swift

appears as: Optional, n Optional
Swift in Depth

This is an excerpt from Manning's book Swift in Depth.

  • Functional programming concepts, such as reduce, flatMap, Optional, and Result, but also how to think in algebraic data types with structs, tuples, and enums
  • Listing 4.2. Optionals are an enum
    // Details omitted from Swift source.
    public enum Optional<Wrapped> {
      case none
      case some(Wrapped)
    }

    Swift 5 offers an official solution to asynchronous error handling. According to rumor, Swift will offer an even better solution once the async/await pattern gets introduced somewhere around Swift version 7 or 8. The community seems to favor asynchronous error handling with the Result type (which is reinforced by Apple’s inclusion of an official Result type since Swift 5). You may already have worked with the Result type and even implemented it in projects. In this chapter, you’ll use one offered by Swift, which may be a bit more advanced than most examples found online. To get the most out of Result, you’ll go deep into the rabbit hole and look at propagation and so-called monadic error handling. The Result type is an enum like Optional, with some differences, so if you’re comfortable with Optional, then Result should not be too big of a jump.

    11.1.1. Result is like Optional, with a twist

    Result is a lot like Optional, which is great because if you’re comfortable with optionals (see chapter 4), you’ll feel right at home with the Result type.

    Swift’s Result type is an enum with two cases: namely, a success case and a failure case. But don’t let that fool you. Optional is also “just” an enum with two cases, but it’s powerful, and so is Result.