I am Using AlamofireObjectMapper i need to make a func that take a Generic parameter like that :
func doSomething < T : BaseMappable > (myCustomClass : T)
{
Alamofire.request("url", method: .get, parameters: nil, encoding: JSONEncoding.default, headers: APIKeys().AuthorizedHeader).responseObject(completionHandler: { ( response :DataResponse<T>) in
let data = response.result.value
if let array = data?.objects
{
for ar in array
{
self.allPromotions.append(ar)
}
}
})
}
but iam getting error :
Use of undeclared type 'myCustomClass' edit as you guys answer me in the comments i put fixed the error but i got another error when iam trying to call this method
i called the method like that
doSomething(myCustomClass: Promotions)
but i got another error
Argument type 'Promotions.Type' does not conform to expected type 'BaseMappable'
and here's my Promotions class
import ObjectMapper
class Promotions : Mappable {
var id:Int?
var workshop_id:Int?
var title:String?
var desc:String?
var start_date:String?
var expire_date:String?
var type:String?
var objects = [Promotions]()
required init?(map: Map){
}
func mapping(map: Map) {
id <- map["id"]
workshop_id <- map["workshop_id"]
title <- map["title"]
desc <- map["desc"]
start_date <- map["start_date"]
expire_date <- map["expire_date"]
type <- map["type"]
objects <- map["promotions"]
}
}
How can i fix that
You need to pass as argument the type of Generic Type T. Try changing
myCustomClass : T
by
myCustomClass : T.Type
The result would look like:
Swift 4:
func doSomething<T>(myCustomClass : T.Type) where T : BaseMappable
{
Alamofire.request("url", method: .get, parameters: nil, encoding: JSONEncoding.default, headers: APIKeys().AuthorizedHeader).responseObject(completionHandler: { ( response :DataResponse<T>) in
let data = response.result.value
if let array = data?.objects
{
for ar in array
{
self.allPromotions.append(ar)
}
}
})
}
Then, you should call the method:
doSomething(myCustomClass: Promotions.self)
Just pass the Promotions.self as the parameter.
doSomething(myCustomClass: Promotions.self)
This'll overcome the error that you are getting in the function call.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With