Search code examples
swiftgenericsswiftuibindingswift-extensions

Swift extension of generic type that is Optional


I would like to extend SwiftUI Binding when its value is any optional type. Is it possible

extension Binding where Value == Optional {
    func filter(_ predicate: @escaping (Value) -> Bool) -> Binding<Value> {
        Binding<Value>(
            get: {
                if predicate(wrappedValue) { return nil }
                return wrappedValue
            },
            set: {
                wrappedValue = $0
            }
        )
    }
}

It works if I use some concrete type like Error? But I want to have more general solution.


Solution

  • You can create a generic T where T? == Value. This means that Value is an optional (and T is the wrapped value of the optional, even though we don't need this type directly).

    Code:

    extension Binding {
        func filter<T>(_ predicate: @escaping (Value) -> Bool) -> Binding<Value> where T? == Value {
            Binding<Value>(
                get: {
                    if predicate(wrappedValue) { return nil }
                    return wrappedValue
                },
                set: {
                    wrappedValue = $0
                }
            )
        }
    }