Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force a generic type parameter to be a class type?

Tags:

generics

swift

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?

like image 438
Mario Guerrieri Avatar asked Jun 08 '14 01:06

Mario Guerrieri


People also ask

How do you indicate that a class has a generic type parameter?

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.

How do you provide a generic parameterized type?

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.

Can a generic class definition can only have one type parameter?

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.

Which operator is used to declare generic type in a class?

We use <T> to create a generic class, interface, and method. The T is replaced with the actual type when we use it.


1 Answers

try:

struct Weak<T:AnyObject>
like image 155
David Berry Avatar answered Oct 09 '22 16:10

David Berry