Swift: Cast generic type into same generic type but with a subclass of associated type

前端 未结 3 838
说谎
说谎 2021-01-12 03:17

Consider these classes:

struct OrderedSet {}

class Exercise: Hashable {}

class StrengthExercise: Exercise {}

class CardioExercise: Exer         


        
3条回答
  •  Happy的楠姐
    2021-01-12 03:29

    As the OrderedSet is of that specific type it cannot be assigned to the more general OrderedSet. Think about what would happen if you tried to append a Cardio exercise to that OrderedSet after assigning it.

    The answer might be to modify append the contents of the strength exercises set to the exercise set rather than assign the whole typed set.

提交回复
热议问题