简体   繁体   English

不能专门化非通用定义

[英]cannot specialize a non-generic definition

I have tried following Cannot explicitly specialize a generic function and I can't get a hold of this我试过遵循Cannot explicitly specialize a generic function 但我无法掌握这个

This is my code这是我的代码

class A<T>{
    func test(){
        self.verify(value : T.self)
    }
    
    func verify<T>(value: T) {
        print("Default")
    }
}

extension A where T == String {
    func verify<T>(value: T){
        print("Str")
    }
}



let o = A<String>()
o.test()

The test is the only available function that can be called.测试是唯一可以调用的function。 When I'm executing this, I get Default not Str.当我执行这个时,我得到的是 Default 而不是 Str。

But according to the generics, I should get Str.但是根据generics,我应该得到Str。 What am I doing wrong here?我在这里做错了什么? What should I do to keep extension A give me Str if T == String如果 T == String,我应该怎么做才能保留扩展名 A 给我 Str

Ok, so I'm learning generics new here.好的,所以我在这里学习 generics new。 And this is what I got,这就是我得到的,

class A<T>{
     func test(){
        print("Def Test")
     
        verifyVal()
    }
    
    func verify() {
        print("Default verifyVal")
    }
}

extension A where T == String {
    func test(){
        print("String")
    }
}
extension A where T == Int {
    func test(){
        print("Int")
    }
}



let o = A<String>()
o.test()

let a = A<Int>()
a.test()

This will give you the expected result这会给你预期的结果

String
Int

So basically overload the test method instead of verify.所以基本上重载测试方法而不是验证。 However, there are some caveats但是,有一些注意事项

  1. If the method test is inherited from another class, say A is a child of N where the method test was originally written, there is no way you can override it in the extensions.如果方法测试是从另一个 class 继承的,假设 A 是最初编写方法测试的 N 的子级,则无法在扩展中覆盖它。

Thats it.而已。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM