How can I create an operator to implement error chaining?

前端 未结 2 1392
青春惊慌失措
青春惊慌失措 2021-01-29 12:54

I want to implement the following operator »:

throwingFunction(arg: T?)».doStuff()

/*  if throwingFunction throws an error:
     print or log the er         


        
相关标签:
2条回答
  • 2021-01-29 13:11

    prefix and postfix are unary operators i.e. they only accept one operand, whereas an infix operator is a binary operator i.e. it accepts two operands.

    So, static func »(value:key:) -> Preferred? is not correct because it's taking two operands whereas you have defined » as a postfix operator.

    0 讨论(0)
  • 2021-01-29 13:30

    For some reason I get "» is not a postfix unary operator" when I don't use the escape syntax. But apart from that it seems to work.

    precedencegroup Chaining {
        associativity: left
    }
    
    infix operator » : Chaining
    
    extension Result {
        static func »<T>(value: Self, key: KeyPath<Success, T>) -> T? {
            switch value {
            case .success(let win):
                return win[keyPath: key]
            case .failure(let fail):
                print(fail.localizedDescription)
                return nil
            }
        }
    }
    
    // I included a custom type so that it could be customizable if needed.  
    enum Err<Wrapped> {
        static func »<T>(value: Self, key: KeyPath<Wrapped, T>) -> T? {
            switch value {
            case .error(let err):
                print(err.localizedDescription)
                return nil
            case .some(let wrapper):
                return wrapper[keyPath: key]
            }
        }
        case error(Error)
        case some(Wrapped)
    }
    
    func errorWrapped() -> Err<String> {
        .some("Hello World")
    }
    
    func pleaseWork()  {
        print(errorWrapped()»\.isEmpty)
    }
    
    0 讨论(0)
提交回复
热议问题