Cannot explicitly specialize a generic function

后端 未结 7 2332
时光取名叫无心
时光取名叫无心 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:25

    You don't need a generic here since you have static types (String as parameter), but if you want to have a generic function call another you could do the following.

    Using Generic methods

    func fetchObjectOrCreate(type: T.Type) -> T {
        if let existing = fetchExisting(type) {
           return existing
        }
        else {
            return createNew(type)
        }
    }
    
    func fetchExisting(type: T.Type) -> T {
        let entityName = NSStringFromClass(type)
         // Run query for entiry
    } 
    
    func createNew(type: T.Type) -> T {
         let entityName = NSStringFromClass(type)
         // create entity with name
    } 
    

    Using a generic class (Less flexible as the generic can be defined for 1 type only per instance)

    class Foo {
    
       func doStuff(text: String) -> T {
          return doOtherStuff(text)
       }
    
       func doOtherStuff(text: String) -> T {
    
       }  
    
    }
    
    let foo = Foo()
    foo.doStuff("text")
    

提交回复
热议问题