我在
swift中创建了一个泛型类,我想使用“AdaptorType”类型初始化一个适配器,但是我收到一个编译错误
class Sample<ItemType,AdaptorType> { var items = Array<ItemType>() let adaptor = AdaptorType() //Error: 'AdaptorType' is not constructible with '()' }
我也尝试在init()中初始化它,但是同样的问题在于
class SampleGnericclass<ItemType,AdaptorType> { var items = Array<ItemType>() let adaptor : AdaptorType init() { adaptor = AdaptorType() //It doesn't work,same error occors here } }
使用通用类型AdaptorType初始化适配器属性的正确方法是什么?万分感谢!
编辑:关于这个问题的完整代码
import UIKit protocol XYManagedobject { } protocol XYNetworkProtocol { typealias ManagedobjectType : XYManagedobject func object(fromItemDictionary dictionary: NSDictionary?) -> ManagedobjectType? func objects(fromEntryDictionary dictionary: NSDictionary?) -> Array<ManagedobjectType>? func actionParameters(page: UInt?) -> (action: String,parameters: Dictionary<String,String>?) func pageSize() -> UInt? // nil for unlimited } class ProductAdaptor : XYNetworkProtocol { var filter = Dictionary<String,String>() typealias ManagedobjectType = XYProductObject func object(fromItemDictionary dictionary: NSDictionary?) -> ManagedobjectType? { //... Will return an object here return nil } func objects(fromEntryDictionary dictionary: NSDictionary?) -> Array<ManagedobjectType>? { //... will return an array of objects here return nil } func actionParameters(page: UInt?) -> (action: String,String>?) { var parameters = filter if page { parameters["page"] = "\(page!)" } return ("product_list",parameters) } func pageSize() -> UInt? { return 100 } } class XYDataManager<ItemType: XYManagedobject,AdaptorType: XYNetworkProtocol> { var objects = Array<ItemType>() let adaptor = ProductAdaptor() //work around,adaptor should be any type conform to XYNetworkProtocol func loadPage(page: UInt?) -> (hasNextPage: Bool,items: Array<ItemType>?) { let fetcher = XYFetchController() let ap = adaptor.actionParameters(page) if let fetchedResult = fetcher.JSONObjectForAPI(ap.action,parameters: ap.parameters) { let npage = fetchedResult["npage"].integerValue var hasNextPage = true if !npage || !page { hasNextPage = false } else if npage <= page { hasNextPage = false } let objects = adaptor.objects(fromEntryDictionary: fetchedResult) return (hasNextPage,(objects as Array<ItemType>?)) } else { return (false,nil) } } }