mohamede1945
mohamede1945

Reputation: 7198

Swift Cast Generics Type

I'm trying to cast a generic type to its super class.

class Foo : NSObject {
}
class Test<T> {
    let value: T
    init(_ value: T) {
        self.value = value
    }
}

let c = Test(Foo())
let v = c as Test<AnyObject>

But on the line

let v = c as Test<AnyObject>

I get 'Foo' is not identical to 'AnyObject'

While I can do that with built-in Arrays

let array1 = [Foo(), Foo()]
let array2 = array1 as [AnyObject]

Upvotes: 2

Views: 619

Answers (1)

Airspeed Velocity
Airspeed Velocity

Reputation: 40973

Arrays are special-cased in Swift to be able to have this behaviour. You won't be able to replicate it with your own classes, unfortunately.

To get similar behaviour, you could give your type another init method:

class Test<T> {
    let value: T
    init(_ value: T) {
        self.value = value
    }

    init<U>(other: Test<U>) {
        // in Swift 1.2 you will need as! here
        self.value = other.value as T
    }
}

let c = Test(Foo())
let v = Test<AnyObject>(other: c)  // this will work ok

Note though that this is unsafe (i.e. will assert at runtime) in cases where you want to convert to an incompatible type (and the alternative, a failable initializer, will also have complications)

Upvotes: 1

Related Questions