I'm trying to figure out a method for avoiding retain cycles when some references in the cycle are held in collections. My idea was to create a wrapper struct
:
struct Weak<T> {
unowned let value: T
init(_ value: T) {
self.value = value
}
}
The issue here is that unowned
and weak
members have to be of a class type (main.swift:3:17: 'unowned' cannot be applied to non-class type 'T'; consider adding a class bound
), but there's no reasonable superclass for me to require that T
inherit from.
Is there any way to force T
to be of a class type without inheriting from a specific other class?
A generic type is declared by specifying a type parameter in an angle brackets after a type name, e.g. TypeName<T> where T is a type parameter.
In order to use a generic type we must provide one type argument per type parameter that was declared for the generic type. The type argument list is a comma separated list that is delimited by angle brackets and follows the type name. The result is a so-called parameterized type.
Multiple parametersYou can also use more than one type parameter in generics in Java, you just need to pass specify another type parameter in the angle brackets separated by comma.
We use <T> to create a generic class, interface, and method. The T is replaced with the actual type when we use it.
try:
struct Weak<T:AnyObject>
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