An array of custom classes that implement generalizations that do not allow you to customize a class with a subclass

I have the following script

class Human {}
class Child: Human {}
class Person<T: Human> {}

var people = [Person<Human>]()
people.append(Person<Child>())

still on line people.append(Person<Child>())I get an error

cannot convert value of type 'Person<Child>' to expected argument type 'Person<Human>'

It's really weird how doing the following works (which seems like an identical situation)

var myArray = [Array<UIView>]()
myArray.append(Array<UIImageView>())

Can someone understand why one way works and not another?

+2
source share
1 answer

In fact, you do not put too much business. Definition:

class Human {}
class Child: Human {}
struct Holder<T> {}

I made Holder a structure, so no one can blame us for deceiving: Array is a structure, Holder is a structure. And I removed your restriction on the placeholder, reducing everything to the maximum possible shape.

Child, Human:

var arr = Array<Human>()
arr = Array<Child>()

Fine. Holder:

var holder = Holder<Human>()
holder = Holder<Child>() // error

parallelism : Array - , Holder - , , , . , ?

, , , , , Apple. Apple , Array , . , . , , , .

, Apple Array , ( Person) , , .

, . . - . Apple , , , , , - (). , , , .

. Swift , T. , , Holder<Child>, Holder<Human>, . Apple .


, :

class Human {}
class Child: Human {}
struct Holder<T> {
    let thing : T
}
let holder : Holder<Human> = Holder(thing:Child()) // fine

, , . : Holder<Human>. , , thing, . . Holder<Human> Holder<Child>, thing , Holder<Child>, Holder<Human>.

+5

All Articles