我可以指定泛型是一个值类型吗? [英] Can I specify that a generic is a value type?
本文介绍了我可以指定泛型是一个值类型吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道我们基本可以用 AnyObject
指定我们的泛型是任何引用类型:
I know that we can essentially specify that our generics be any reference type by using AnyObject
:
class Foo<T: AnyObject> {
// ...
}
但有没有办法指定我们的泛型只应该是 value 类型,并且不允许使用引用类型?
But is there a way to specify that our generics should only be value types, and not allow reference types?
推荐答案
// some code for testing
class C { } // just a simple class as an example for a reference type
var c = C()
var d: Double = 0.9 // a value type
解决方案1通过扩展
Solution 1 via extension
protocol ValueType { }
extension Double : ValueType { }
extension Int : ValueType { }
// ... all value types to be added
func printT1 <T: ValueType> (input: T) {
println("\(input) is value")
}
printT1(d) // Does work
//printT1(c) // Does not work
但正如评论中提到的那样,它正在工作但不可行,因为用户定义值类型必须实现此协议。
But as mentioned in the comments, it is working but not feasible, because user defined value types have to implement this protocol.
func printT <T: AnyObject> (input: T) {
println("\(input) is reference")
}
func printT <T: Any> (input: T) {
println("\(input) is value")
}
解决方案3通过 assert
另一个解决方案可以通过 assert
func printT <T: Any> (input: T) {
print("\(input) is " + ((T.self is AnyObject) ? "reference" : "value"))
}
Solution4 via where
子句
我认为这将是最好的解决方案。不幸的是,不可能有
"Solution" 4 via where
clauses
This would be the best solution, I think. Unfortunately, it is not possible to have
func printT <T: Any where T: ~AnyObject > (input: T) {
println("\(input) is value")
}
或类似。也许在未来的Swift版本中可能会这样。
or similar. Maybe it will be possible in future releases of Swift.
这篇关于我可以指定泛型是一个值类型吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文