Swift中的泛型选择器视图

时间:2019-01-05 18:17:15

标签: ios swift generics

我正在尝试使用泛型创建通用的UI选择器。作为实现的一部分,我创建了要在UIPicker中显示的GenericRow对象。但是我面临一些问题。它可能是基本的,但找不到。

struct GenericRow<T> {
    let type: T
    let title: String
    public init(type: T, title: String) {
        self.type = type
        self.title = title
    }
 }

接下来是GenericDataSource,用于处理UIPickerViewDataSource和UIPickerViewDelegate。

class GenericPickerDataSource<T>: NSObject, UIPickerViewDelegate, UIPickerViewDataSource {

    public var items: [GenericRow<T>]

    public init(withItems items: [GenericRow<T>]) {
        self.items = items
    }

    public func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }

    public func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return items.count
    }

    public func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return items[row].title
    }
}

然后,我正在创建一个管理器来处理选择器的显示/隐藏功能。请注意,这也是通用的,对GenericRow类型一无所知。

class GenericPickerManager {
    static func showPicker(_ dataSource: GenericPickerDataSource<Any>) {}

    static func hidePicker() {}
}

示例输入:

struct State {
    let identifier: String
    let name: String
}

let CA = State(identifier: "CA", name: "California")
let CLT = State(identifier: "CLT", name: "Charlotte")
let IL = State(identifier: "IL", name: "Illinois")

let states = [CA, CLT, IL]

let items = states.map {
    GenericRow<State>(type: $0, title: $0.name)
}

let dataSource = GenericPickerDataSource(withItems: items)

现在,当我尝试向班级展示选择器时,出现错误。

GenericPickerManager.showPicker(dataSource)
  

无法将类型GenericPickerDataSource 的值转换为   预期的参数类型GenericPickerDataSource

如何解决此问题?

1 个答案:

答案 0 :(得分:2)

Any和泛型不能很好地协同工作。使GenericPickerManager也通用:

class GenericPickerManager<T> {
    static func showPicker(_ dataSource: GenericPickerDataSource<T>) {}

    static func hidePicker() {}
}