I know that we can essentially specify that our generics be any reference type by using AnyObject
:
class Foo {
// ...
}
// 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
extension
protocol ValueType { }
extension Double : ValueType { }
extension Int : ValueType { }
// ... all value types to be added
func printT1 (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 (input: T) {
println("\(input) is reference")
}
func printT (input: T) {
println("\(input) is value")
}
assert
Another solution could be via assert
func printT (input: T) {
print("\(input) is " + ((T.self is AnyObject) ? "reference" : "value"))
}
where
clausesThis would be the best solution, I think. Unfortunately, it is not possible to have
func printT (input: T) {
println("\(input) is value")
}
or similar. Maybe it will be possible in future releases of Swift.