我有以下结构
struct APIResource<T> {
let urlRequest: NSMutableURLRequest
let resource: T
let parse: (NSData) -> T
}
我也有以下视图控制器。要求网络堆栈从网络加载资源是工作。完成后,它将调用build函数来构建适当的视图控制器,并将其添加为子视图控制器 final class LoadingVCL: UIViewController {
init<T>(_ resources: APIResource<T>, build: ((T) -> UIViewController)) {
super.init(nibName: nil, bundle: nil)
//ask the network stack for the data
//once data is loaded, I call the build closure
//to return a view controller and add it as a childviewcontroller
}
我正在努力扩展此LoadingVC以接受一系列资源并在添加视图控制器之前加载它们。我在遵循this教程时遇到了这个问题。
编辑一个
例如,假设我有以下资源
let resourceOne = APIResource<Int>(urlRequest: NSMutableURLRequest(), resource: 1, parse: { _ in return 1})
let resourceTwo = APIResource<Double>(urlRequest: NSMutableURLRequest(), resource: 1, parse: { _ in return 1})
let resourceThree = APIResource<String>(urlRequest: NSMutableURLRequest(), resource: "1", parse: { _ in return "1"})
我正在尝试为视图控制器找到一种接受具有不同类型的资源数组的方法。任何帮助,将不胜感激。
谢谢
最佳答案
一旦创建了APIResource<T>
实例,它就会具有分配的类型,并且不再通用。例如,APIResource<String>
与APIResource<Double>
的类型不同。要创建混合类型的数组,您需要使用协议,例如
protocol APIResourceProtocol{}
struct APIResource<T>:APIResourceProtocol {
let urlRequest: NSMutableURLRequest
let resource: T
let parse: (NSData) -> T
}
let resourceOne = APIResource<Int>(urlRequest: NSMutableURLRequest(), resource: 1, parse: { _ in return 1})
let resourceTwo = APIResource<Double>(urlRequest: NSMutableURLRequest(), resource: 1, parse: { _ in return 1})
let resourceThree = APIResource<String>(urlRequest: NSMutableURLRequest(), resource: "1", parse: { _ in return "1"})
let arr:[APIResourceProtocol] = [resourceOne, resourceTwo, resourceThree]
当然,这可能不是您想要的,因为您可能希望能够遍历数组并使用某些方法。不幸的是,协议不是通用的,因此只能是非通用类型,您可以利用这种行为类型,例如
protocol APIResourceProtocol {
var urlRequest: NSMutableURLRequest {get set}
}
struct APIResource<T>:APIResourceProtocol {
var urlRequest: NSMutableURLRequest
let resource: T
let parse: (NSData) -> T
}
protocol ResourceType {}
let resourceOne = APIResource<Int>(urlRequest: NSMutableURLRequest(), resource: 1, parse: { _ in return 1})
let resourceTwo = APIResource<Double>(urlRequest: NSMutableURLRequest(), resource: 1, parse: { _ in return 1})
let resourceThree = APIResource<String>(urlRequest: NSMutableURLRequest(), resource: "1", parse: { _ in return "1"})
let arr:[APIResourceProtocol] = [resourceOne, resourceTwo, resourceThree]
arr.map{$0.urlRequest}