swift - 尝试在 Swift 中将泛型类型作为参数传递

标签 swift generics alamofire

我正在使用 AlamofireObjectMapper 我需要制作一个带有通用参数的函数:

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)
                }
            }

        })


}

但我收到错误:

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

我是这样调用方法的

doSomething(myCustomClass: Promotions)

但是我得到了另一个错误

Argument type 'Promotions.Type' does not conform to expected type 'BaseMappable'

这是我的促销类(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"]
        }




}

我该如何解决

最佳答案

您需要将通用类型 T 的类型作为参数传递。尝试更改

myCustomClass : T

myCustomClass : T.Type

结果如下:

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)
                    }
                }

            })
    }

然后,您应该调用方法:

doSomething(myCustomClass: Promotions.self)

关于swift - 尝试在 Swift 中将泛型类型作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44117301/

相关文章:

ios - Alamofire参数编码,字典中的字典

ios - 如何将高分保存并打印到下一个场景?

DbSet<something> 的 C# 泛型

ios - siwfty json 解析失败

java - 推断泛型类中的参数类型,这些参数类型是所提供参数的嵌套泛型类型

java - Class 和 Class<?> 之间的真正区别(如果有的话)是什么?

ios - Alamofire: 'weak' 无法应用于非类类型错误

swift - 在 Swift 3 中以编程方式设置内容过滤器

ios - map View :rendererForOverlay delegate method never called when addOverlay is called on MKMapView

ios - UITableView 过滤