我在
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) } } }
解决方法
并不是所有的对象都可以被初始化,而不是你想要的参数.你必须将初始化的实例带到你的类的初始化器
您还可以定义自己的协议,需要一个空的初始化器(通过向其中添加init),并将AdapterType限制为该协议