Swift Generics & Upcasting

I have a quick question about generics in Swift. The problem is that I am trying to save a variable that takes a general parameter as a parameter, but I cannot drop it to the type that it is limited to. This is best explained in a short example:

class Foo { }

class Thing<T: Foo> {
    func produceBar() -> Bar {
        return Bar(aThing: self as! Thing<Foo>)
    }
}

class Bar {
    var thing: Thing<Foo>

    init(var aThing: Thing<Foo>) {
        self.thing = aThing
    }
}

The above code creates an error: "Cast from Thing<T> to unrelated type Thing<Foo> always fails"

Should this never fail, since T is limited to a subclass of Foo? I must not understand how generics work in Swift, any guidance or help would be greatly appreciated!

+2
source share
1 answer

- . , : , Basket<Apple> Basket<Fruit>, Apple Fruit. .

:

class Fruit {}
class Apple: Fruit {}
class Orange: Fruit {}

class Basket<T: Fruit> {
    private var items: [T]
    func add(item: T) {
        items.append(item)
    }
    init() {}
}

func addItem<T: Fruit>(var basket: Basket<T>, item: T) {
    basket.add(item)
}

let basket:Basket<Apple> = Basket()

addItem(basket as Basket<Fruit>, Orange())

, Basket<Apple> Basket<Fruit>, .

+4

Source: https://habr.com/ru/post/1695868/


All Articles