gpt4 book ai didi

ios - 如何在 Swift 中通过泛型类型构造属性?

转载 作者:IT王子 更新时间:2023-10-29 05:27:44 26 4
gpt4 key购买 nike

我在 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, parameters: Dictionary<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)
}
}
}

最佳答案

并非所有对象都可以像您尝试的那样在没有参数的情况下进行初始化。你必须将一个初始化的实例带到你类的初始化器中

你也可以定义你自己的协议(protocol),它需要一个空的初始值设定项(通过向它添加 init)并限制 AdapterType 为该协议(protocol)

关于ios - 如何在 Swift 中通过泛型类型构造属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24190837/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com