简体   繁体   English

在Swift中使用泛型类型推断

[英]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). 我收到字符串“chocolatechip”的错误,说它无法转换(等等)。 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) 我相信它无法弄清楚T是什么,因为当我从函数中返回goodie并在调用它时将其赋值给变量(或者只是执行转换)时它会起作用

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. 有没有什么方法可以让我快速知道它是什么类型没有这种方式的hacky方式。

If you add a type annotation to the closure parameter then the compiler can infer the generic type T : 如果向闭包参数添加类型注释,则编译器可以推断泛型类型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)")
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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