Swift闭包类型转换

时间:2016-04-09 15:19:05

标签: swift closures

我定义了协议MessageProtocol,而类MessageAMessageB采用了协议。

我希望将(MessageA) -> Void之类的闭包转换为(MessageProtocol) -> Void

有代码,解决方案1 ​​ 2 无法正常运作。

protocol MessageProtocol {
    func doSomething()
    static func parserFromData() -> MessageProtocol
}

class MessageA: MessageProtocol {
    func doSomething() {
        print("this is A class")
    }

    func functionInA() {
        print("funciton in A")
    }

    static func parserFromData() -> MessageProtocol {
        return MessageA()
    }
}

class MessageB: MessageProtocol {
    func doSomething() {
        print("this is B class")
    }

    func functionInB() {
        print("funciton in b")
    }

    static func parserFromData() -> MessageProtocol {
        return MessageB()
    }
}

// private function .network callback
func callback(type: MessageProtocol.Type, handler: (MessageProtocol?) -> Void) -> Void {
    let obj = type.parserFromData()
    handler(obj)
}

// public function
func response<T: MessageProtocol>(type: T.Type, handler: (T?) -> Void) -> Void {

    // solution 1. compile error
//    let handler: (ABProtocol) -> Void = handler     // compile error
//    callback(type, handler: handler)

    // solution 2. runtime error
//    let handler = handler as! (ABProtocol) -> Void  // runtime error
//    callback(type, handler: handler)

    // solution 3. now i use
    callback(type) { obj in
        handler(obj as? T)
    }
}

response(MessageA.self) { a in
    guard let a = a else {
        return
    }
    a.doSomething()
    a.functionInA()
}

response(MessageB.self) { b in
    guard let b = b else {
        return
    }
    b.doSomething()
    b.functionInB()
}

0 个答案:

没有答案