Cannot explicitly specialize a generic function

后端 未结 7 2309
时光取名叫无心
时光取名叫无心 2020-12-04 11:06

I have issue with following code:

func generic1(name : String){
}

func generic2(name : String){
     generic1(name)
}
         


        
7条回答
  •  抹茶落季
    2020-12-04 11:32

    So far, my personal best practise used @orkhan-alikhanov 's answer. Today, when looking at SwiftUI and how .modifier() and the ViewModifier is implemented, I found another way (or is it more a workaround?)

    Simply wrap the second function into a struct.

    Example:

    If this one gives you the "Cannot explicitly specialize a generic function"

    func generic2(name: String){
         generic1(name)
    }
    

    This one might help. Wrap the declaration of generic1 into a struct:

    struct Generic1Struct {
        func generic1(name: String) {## do, whatever it needs with T ##}
    }
    

    and call it with:

    func generic2(name : String){
         Generic1Struct().generic1(name: name)
    }
    

    Remarks:

    • I don't know if it helps in any possible case, when this error message occurs. I just know, that I was stuck many times when this came up. I do know, that this solution helped today, when the error-message came up.
    • The way Swift handles Generics is for me still confusing.
    • This example and the workaround with the struct is a good example. The workaround here has not a bit more information - but passes the compiler. Same information, but different results? Then something is wrong. If it is a compiler-bug it can get fixed.

提交回复
热议问题