is it possible to create a generic closure in Swif

2020-02-27 02:40发布

func myfunc<T>(i:T) -> T {
    return i
}

is it possible to make this generic function a closure?

let myfunc = { <T>(i:T) -> T in
    return i
}

this doesn't work...

3条回答
叼着烟拽天下
2楼-- · 2020-02-27 03:06

No, because variables and expressions can't be generic. There are only generic functions and generic types.


To clarify: In some languages you can have types with a universal quantifier, like forall a. a -> a. But in Swift, types cannot have a universal quantifier. So expressions and values cannot be themselves generic. Function declarations and type declarations can be generic, but when you use such a generic function or an instance of such a generic type, some type (which could be a real type or a type variable) is chosen as the type argument, and thereafter the value you get is no longer itself generic.

查看更多
3楼-- · 2020-02-27 03:13

Probably you need something like this.

Type declaration:

typealias ResultClosure<T> = (ResultCode, String?, T?) -> Void

Function declaration:

func loginUser(userName: String, password: String, resultHandler: ResultClosure<TokenModel>?)

Usage:

    NetConnector.shared.loginUser(userName: userName ?? "", password: password ?? "") { (code, message, data) in
        self.display?.unlockScreen()
        if code == .success {
            if let activeToken = data {
                AppData.shared.userToken = activeToken
            }
            self.display?.showHome()
        } else {
            self.display?.showError(errorMessage: message)
        }
    }
查看更多
Anthone
4楼-- · 2020-02-27 03:19

I have found some alternative way , you can use Anyobject in your closure and pass any values to your method .

typealias genericCompletion<T:AnyObject> = ((Bool,T,String) -> Void)
struct Student {
    var name:String = "Kishore"
    var age : String = "125"
}
class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        self.createAGenericReturn { (success, object, message) in

        }

        self.createStructGeneric { (success, student, message) in

        }

    }


    func createAGenericReturn(callback:@escaping(genericCompletion<AnyObject>)){
        callback(true,434.433 as AnyObject,"kishoreTest")
    }

    func createStructGeneric(callback:@escaping(genericCompletion<AnyObject>)){
        callback(true,Student.init() as AnyObject,"kishoreTest")
    }

}

Here you can see I mentioned Generic as Anyobject typealias genericCompletion = ((Bool,T,String) -> Void) , So you can pass any values to it .

查看更多
登录 后发表回答