Mario Guerrieri
Mario Guerrieri

Reputation: 53

Force a generic type parameter to be a class type?

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?

Upvotes: 5

Views: 1783

Answers (1)

David Berry
David Berry

Reputation: 41226

try:

struct Weak<T:AnyObject>

Upvotes: 10

Related Questions