如何调用此通用函数?

时间:2015-06-03 20:19:00

标签: swift generics protocols type-inference

我只是想到了这个试图找出Swift泛型。我想出了以下测试代码,我想打电话给f()。在这种情况下,我无法弄清楚如何告诉编译器TClassy

protocol Prot {
    func doSomething()
    static func instance() -> Prot
}

class Classy: Prot {

    func doSomething() {
        print("here")
    }

    static func instance() -> Prot {
        return Classy()
    }
}

func f<T: Prot>() {
    T.instance().doSomething()
}

f() // error
f<Classy>() // error

2 个答案:

答案 0 :(得分:4)

试试这个:

f<T: Prot>(t: T.Type) {
    t.instance().doSomething()
}

f(Classy.self)

我现在不在我可以测试它的地方,但我过去使用过这种技术而且它很有效。

答案 1 :(得分:1)

@Roman Sausarnes的回答是正确的,但您可以改为使用初始化,而不是使用方法instance

protocol Prot {
    func doSomething()
    init()
}

class Classy: Prot {
    func doSomething() {
        println("Did something")
    }

    // The required keyword ensures every subclass also implements init()
    required init() {}
}

func f<T: Prot>(Type: T.Type) {
    Type().doSomething()
}

f(Classy.self) // Prints: "Did something"
相关问题