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

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

Consider these classes:

struct OrderedSet {}

class Exercise: Hashable {}

class StrengthExercise: Exercise {}

class CardioExercise: Exer         


        
3条回答
  •  感情败类
    2021-01-12 03:35

    I am afraid this is not currently possible as of Swift 2.1. Only the following conversions are supported

    • Built in collections types are covariant on their element type.
    • Conversions between function types are supported, exhibiting covariance in function result types and contravariance in function parameter types. (Cf. Xcode 7.1 Release Notes)

    As Objective-C's generics support type variance, and given the progress made on function type conversions in Swift 2.1, I believe there is reason to believe type variance support will be added to Swift in the future. In the mean time, remember to file a radar, like jlieske has.

    In the mean time you will have to copy the collection or use one of the builtin collection types.

    Update since Swift become open source: I believe the Complete generics section of Swift 3.0 Dev Roadmap indicates type variance will be addressed in 3.0. While type variance is not specifically called out, special cased exceptions in the standard library (which includes type variance) are.

提交回复
热议问题