I know that we can essentially specify that our generics be any reference type by using AnyObject
:
class Foo<T: AnyObject> {
// ...
}
But is there a way to specify that our generics should only be value types, and not allow reference types?
Use the IsGenericType property to determine whether the type is generic, and use the IsGenericTypeDefinition property to determine whether the type is a generic type definition. Get an array that contains the generic type arguments, using the GetGenericArguments method.
It will give a compile-time error if you try to instantiate a generic type using a type that is not allowed by the specified constraints. You can specify one or more constraints on the generic type using the where clause after the generic type name.
The actual type arguments of a generic type are. reference types, wildcards, or. parameterized types (i.e. instantiations of other generic types).
The generic value variable is a type of variable with a wide range that can store any kind of data, including text, numbers, dates and arrays, and is particular to UiPath Studio. Generic value variables are automatically converted to other types, in order to perform certain actions.
// 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 <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")
}
assert
Another solution could be via assert
func printT <T: Any> (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 <T: Any where T: ~AnyObject > (input: T) {
println("\(input) is value")
}
or similar. Maybe it will be possible in future releases of Swift.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With