2

我正在尝试在 Swift 中实现责任链模式。

public class Chain<T, U> {
    private var command: (T?, (U?) -> Void) -> Void
    private var runCommand: (() -> Void)?
    private var nextCommand: ((U?) -> Void)?

    private init(command: (T?, (U?) -> Void) -> Void) {
        self.command = command
    }

    private func next(u: U?) {
        self.nextCommand?(u)
    }

    func then<V>(command: (U?, (V?) -> Void) -> Void) -> Chain<U, V> {
        let c = Chain<U, V>(command: command)

        self.nextCommand = { command($0, c.next) }
        c.runCommand = self.runCommand

        return c
    }

    func endWith(command: (U?) -> Void) {
        self.nextCommand = command
        self.runCommand!()
    }

    static func build<V>(command: ((V?) -> Void) -> Void) -> Chain<AnyObject, V> {
        let c = Chain<AnyObject, V>(command: { _, next in command(next) })
        c.runCommand = { command(c.next) }
        return c
    }
}

我的课程没有引发任何编译错误,但一个简单的用例(如下面的)不起作用。它引发以下错误:error: cannot invoke 'endWith' with an argument list of type '((_?) -> ()) ; expected an argument list of type '((U?) -> Void)'

任何想法?

Chain.build { next in
    print("Foo")
    next("Bar")
}
.then { o, next in
    print(o)
    next(15)
}
.endWith { o in
    print(o)
}

我知道这是 Swift 中泛型使用的一个极端案例。但是,由于不可能显式地专门化泛型类型,所以到目前为止我还没有找到任何解决方案。

4

1 回答 1

3

编译器无法推断示例中的类型。您只需要在它们不明确的地方指定它们:

Chain<String,Int>.build { next in
  print("Foo")
  next("Bar")
  }
  .then { (o: String?, next: Int? -> Void) in
    print(o)
    next(15)
  }
  .endWith { o in
    print(o)
}
于 2015-12-07T21:26:26.050 回答