在Swift中,如何将函数一般地限制为理解T + T的类型 [英] In Swift, how to generically limit function to types that understand T + T
问题描述
class funccalc {$ b我有一个泛型函数可以在两个值上使用加号运算符。 $ b func doAdd< T>(x:T,y:T) - > T {
return x + y
}
}
let a = funccalc()
println(a.doAdd(1,y:4))
println(a.doAdd(23.54,y:200))
c $ c> return x + y
我唯一的选择是遵循这个答案中的建议:https://stackoverflow.com/a/24047239/67566 ,并创建我自己的协议为 Int
和字符串
会定义运算符? 答案建议。创建一个协议供您使用,并扩展您想要使用它的所有类。然后确保T在方法签名中实现了该协议。
不能使用可添加协议,因为在swift中没有一个协议。 swift库实际上为每个有效的加法操作创建一个函数+。按住Command键点击类似于Int的东西,看看所有这些是在哪里定义的。它看起来像这样:
$ $ $
func +(lhs:Int8,rhs: Int8) - > Int8
func +(lhs:UInt16,rhs:UInt16) - > UInt16
func +(lhs:Int16,rhs:Int16) - > Int16
func +(lhs:UInt32,rhs:UInt32) - > UInt32
func +(lhs:Int32,rhs:Int32) - > Int32
//等等...
I would like to have a generic function that can use the plus operator on two values.
class funccalc {
func doAdd<T>(x:T,y:T) -> T {
return x + y
}
}
let a = funccalc()
println(a.doAdd(1, y: 4))
println(a.doAdd(23.54, y:200))
I get an error on return x + y
Is my only option to follow the suggestion in this answer: https://stackoverflow.com/a/24047239/67566, and create my own protocol as Int
and String
would define the operator?
You should do as that answer suggested. Create a protocol for your use and extend all of the classes that you want to use it. Then make sure T implements that protocol in your method signature.
You can't use an "addable" protocol because there isn't one in swift. The swift library actually creates a function + for each valid addition operations. Command-click on something like Int to see where all of these are defined. It will look something like this:
//....
func +(lhs: Int8, rhs: Int8) -> Int8
func +(lhs: UInt16, rhs: UInt16) -> UInt16
func +(lhs: Int16, rhs: Int16) -> Int16
func +(lhs: UInt32, rhs: UInt32) -> UInt32
func +(lhs: Int32, rhs: Int32) -> Int32
//etc...
这篇关于在Swift中,如何将函数一般地限制为理解T + T的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!