Swift: overriding typealias inside subclass

后端 未结 2 1693
耶瑟儿~
耶瑟儿~ 2021-02-19 00:56

So I was thinking about a custom pattern in my project, but I can\'t get it to work. The main idea is to change the typealias on every subclass to get access to the

2条回答
  •  无人及你
    2021-02-19 01:03

    Unfortunately there is no good workaround for this problem.

    The main idea to override the typealias would work in this case but consider the following:

    protocol TakeAndGet {
        typealias T
        func take(value: T)
        func get() -> T
    }
    
    class FirstClass: TakeAndGet {
        typealias T = FirstClass
    
        var property = 0
    
        func take(value: T) {
            value.property = 4
        }
    
        func get() -> T {
            return FirstClass()
        }
    }
    
    class SecondClass: FirstClass {
    
        typealias T = SecondClass
    
        var property2 = "hello"
    }
    

    If the typealias of the SecondClass overrides the other one the take method would work since it takes a subclass which can be treated as the superclass. But the get method cannot implicitly convert FirstClass to SecondClass. Therefore it is not possible to override a typealias.

    Now if we want to override the get function with get() -> SecondClass it wouldn't work since it has not the same signature as the one in the superclass. In addition we inherit the get method which results in an ambiguous use:

    SecondClass().get() // which type gets returned? SecondClass or FirstClass
    

    So you have to try a different approach.

提交回复
热议问题