[英]How to return a default value for a generic parameter in a function in Swift?
I'm using generics to dynamically assign the type of the value that the response should be, at the call site of the function. 我正在使用泛型在函数的调用位置动态分配响应应为的值的类型。
How can I set a default value for generic parameter, so that no one could hypothetically come along and insert an object as response when they won't get one? 我如何为通用参数设置默认值,以使没有人假设不会出现并在没有对象时插入对象作为响应?
Hopefully the code speaks for itself and makes more sense than I did. 希望代码能说明一切,并且比我有更多的道理。
Other info: 其他资讯:
Inside the method below, if its a GET request, I initialize T with the json response. 在下面的方法中,如果它是GET请求,则使用json响应初始化T。 As you see the generic has to conform to QueryType protocol, which just contains an initializer, so each object that is T, has an initializer to handle response in its own way. 如您所见,泛型必须符合QueryType协议,该协议仅包含一个初始化程序,因此每个T对象都具有一个初始化程序以自己的方式处理响应。
func fireRequest<T: QueryType>(_ request: FirebaseRequest, completion: @escaping (_ data: [T]? = [], _ error: FirebaseError?) -> Void ) {
// setting default value to data param throws error.
}
Successful use case: 成功的用例:
client.fireRequest(FirebaseRequest.observe(path: path), completion: { (data: [User], error: FirebaseError? ) in
// Since I infer 'T' to be of type User, i can expect a collection of users, or single user as my response. This is what I want.
})
Error Use case: 错误用例:
client.fireRequest(FirebaseRequest.setValue(path: path, value: locationData), completion: { (_, error: FirebaseError? ) in
// error: generic parameter 'T' could not be inferred.
// In this case, I am posting some data to database, so I dont expect a response, but putting underscore throws error.
})
I am not exactly sure what you are asking but you can use T()
to generate the defualt value for the type. 我不确定您要问的是什么,但可以使用T()
生成该类型的默认值。
As for the underscore it is because (_, FirebaseError?)->Void
is not the same type as ([T], FirebaseError?)->Void
. 至于下划线,是因为(_, FirebaseError?)->Void
与([T], FirebaseError?)->Void
。 So your closure should be 所以你应该关闭
{(_:[AnyObject]?, error: FirebaseError?) in code }
If you want this to use generics you would need to define some function like 如果要使用泛型,则需要定义一些函数,例如
func errorCaseCompletetion<T>( _ : [T]?, error: FirebaseError?){
//code
}
And then you just pass the function name as the completetion block. 然后,您只需传递函数名称作为完成块即可。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.