Cannot explicitly specialize a generic function

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

    Swift 5

    Typically there are many ways to define generic functions. But they are based on condition that T must be used as a parameter, or as a return type.

    extension UIViewController {
        class func doSomething() -> T {
            return T()
        }
    
        class func doSomethingElse(value: T) {
            // Note: value is a instance of T
        }
    
        class func doLastThing(value: T.Type) {
            // Note: value is a MetaType of T
        }
    }
    

    After that, we must provide T when calling.

    let result = UIViewController.doSomething() as UIImageView // Define `T` by casting, as UIImageView
    let result: UILabel = UIViewController.doSomething() // Define `T` with property type, as UILabel
    UIViewController.doSomethingElse(value: UIButton()) // Define `T` with parameter type, as UIButton
    UIViewController.doLastThing(value: UITextView.self) // Define `T` with parameter type, as UITextView
    

    Ref:

    1. http://austinzheng.com/2015/01/02/swift-generics-pt-1/
    2. https://dispatchswift.com/type-constraints-for-generics-in-swift-d6bf2f0dbbb2

提交回复
热议问题