Type inference with Generics in Swift

I have this code

func getMeGoodies<T>(String:goodieName, callback:(goodie:T) -> ()) {
   var goodie:T = //get it from the jug
   callback(goodie)
}

      

And somewhere I want to call it

self.getMeGoodies("chocolatechip", callback: { (goodie) -> () in
            println("eat the \(goodie)")
        })

      

I am getting an error on the line "chocolate" saying it cannot convert (blah blah). I believe he cannot figure out what this T

is because it works when I return goodie

from a function and assign it to a variable when I call it (or just when I cast)

var chocolateChip:Goodie =  self.getMeGoodies("chocolatechip", callback: { (goodie) -> () in
            println("eat the \(goodie)")
        }) 

      

or

self.getMeGoodies("chocolatechip", callback: { (goodie) -> () in
            println("eat the \(goodie)")
        }) as Goodie

      

Is there any way I can give to quickly find out what type it is without using a hacky way of doing it.

+3


source to share


1 answer


If you add a type annotation to the closure parameter, then the compiler can infer the generic type T

:

self.getMeGoodies("chocolatechip", callback: { (goodie : Goodie) -> () in
    println("eat the \(goodie)")
})

      



Another method is to pass the type as an argument to the method:

func getMeGoodies<T>(type : T.Type, goodieName : String, callback:(goodie:T) -> ()) {
    var goodie:T = 0 //get it from the jug
    callback(goodie: goodie)
}

self.getMeGoodies(Goodie.self, goodieName: "chocolatechip", callback: { (goodie)  in
    println("eat the \(goodie)")
})

      

+4


source







All Articles