简体   繁体   中英

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 this

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

I am getting an error at the string "chocolatechip" saying it can't convert (blah blah). I believe it is not able to figure it out what T is because it works when I return the goodie from the function and assign it to a variable when calling it (or simply do a casting)

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 let swift know what type it is without the sorta hacky way of doing it.

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)")
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM