swift - 将泛型类型传递给具有更具体扩展要求的方法

时间:2017-04-27 03:24:26

标签: swift generics protocols

因此标题有点奇怪,但这是我要做的事情的基础。我想创建一个函数,可以确定给定的泛型类型是否从特定协议扩展,然后通过该类型传递给更具体的方法进行处理。这将使用swift编程语言来实现。

我想在下面实现的Psuedo代码:

func doStuff<T>(callback: Callback<T>) {
    // Pseudo code of what I want to achieve as I'm not sure the syntax
    // nor if it's even possible
    if T extends Protocol {
        let tExtendsProtocolType = T.Type as Protocol
        mapStuffSpecific<tExtendsProtocolType>(callback: callback)
    } else {
        // Standard Use Case
    }
}

func doStuffSpecific<T: Protocol>(callback: Callback<T> {

}

提前致谢

编辑1

typealias Callback<T> = (T) -> Void

protocol Protocol {}

struct A {}
struct B: Protocol {}

// I want to be able to use this to do some common set up then call into either doStuff<T> or doStuff<T: Protocol>
func tryDoStuff<T>(callback: Callback<T>) {
    // Do some common setup then call this
    doStuff(callback: callback)
}

func doStuff<T>(callback: Callback<T>) {
    print("doStuff")
}

func doStuff<T: Protocol>(callback: Callback<T>) {
    print("doStuffSpecific")
}

let callbackA: Callback<A> = { _ in } // Just an empty closure
let callbackB: Callback<B> = { _ in }

tryDoStuff(callback: callbackA) // prints doStuff
tryDoStuff(callback: callbackB) // prints doStuffSpecific

1 个答案:

答案 0 :(得分:1)

Swift的过载分辨率算法已经优先考虑了最具体的过载。这是一个例子:

typealias Callback<T> = (T) -> Void

protocol Protocol {}

struct A {}
struct B: Protocol {}

func doStuff<T>(callback: Callback<T>) {
    print("doStuff")
}

func doStuff<T: Protocol>(callback: Callback<T>) {
    print("doStuffSpecific")
}

let callbackA: Callback<A> = { _ in } // Just an empty closure
let callbackB: Callback<B> = { _ in }


doStuff(callback: callbackA) // prints doStuff
doStuff(callback: callbackB) // prints doStuffSpecific