vrwim
vrwim

Reputation: 14340

How can I call this generic function?

I just thought of this trying to figure out Swift generics. I have come up with the following test code where I'd like to call f(). I can't figure out how I can tell the compiler that the T is Classy in this case.

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

Upvotes: 1

Views: 62

Answers (2)

ABakerSmith
ABakerSmith

Reputation: 22939

@Roman Sausarnes' answer is correct, but instead of having the method instance, you could instead use an initialiser:

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"

Upvotes: 1

Aaron Rasmussen
Aaron Rasmussen

Reputation: 13316

Try this:

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

f(Classy.self)

I'm not in a place where I can test it right now, but I have used this technique in the past and it worked.

Upvotes: 4

Related Questions