Home > front end >  What does the swift keyword Wrapped mean in the Optional extension?
What does the swift keyword Wrapped mean in the Optional extension?

Time:10-17

What does the swift keyword Wrapped mean in the Optional extension?

extension Optional {
    func flatMap<U>(_ transform: (Wrapped) -> U?) -> U? {
        guard let x = self else { return nil }
        return transform(x)
    }
}

CodePudding user response:

In extensions, the generic parameters of the type that you are extending can be referenced by just writing their simple names, and notice that Optional is a generic type.

@frozen enum Optional<Wrapped>

So Wrapped in the function declaration refers to the generic parameter declared there.

As you may know, optional types are usually written as T? (where T is some type), which is a syntactic sugar for Optional<T>. For example, Int? is the same as Optional<Int>, and String? is the same as Optional<String>, etc.

In other words, Wrapped basically just means the type that precedes the ?, whatever that may be. If you have a String? (aka Optional<String>), then the signature of flatMap for that would be:

func flatMap<U>(_ transform: (String) -> U?) -> U?

CodePudding user response:

There is no keyword "Wrapped." This is a type parameter. This is similar to runtime parameters. If you see:

func f(x: Int) { ... }

x is not a keyword. It's just a parameter name. In the same way, Optional is defined as:

enum Optional<Wrapped>

"Wrapped" is just the type parameter passed to Optional. So in this extension:

func flatMap<U>(_ transform: (Wrapped) -> U?) -> U? {

"Wrapped" just refers to whatever Optional is wrapping.

  • Related