创建一个swift泛型数组

时间:2016-12-03 06:44:00

标签: ios swift generics

我有以下结构

struct APIResource<T> {
    let urlRequest: NSMutableURLRequest
    let resource: T
    let parse: (NSData) -> T
 }

我还有以下视图控制器。它的工作是要求网络堆栈从网络加载资源。完成后,它将调用构建函数来构建适当的视图控制器并将其添加为子视图控制器

 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教程时遇到了这个问题。

编辑一个

对于Instance,假设我有以下资源

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

我试图找出一种方法让视图控制器接受具有不同类型的资源数组。

任何帮助将不胜感激。 感谢

1 个答案:

答案 0 :(得分:0)

只要创建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}