我在使用快速泛型时遇到了一些问题。
以下代码可以很好地进行编译,但是if let item = row as? SelectionInputControl<Any> {
行无法像我想象的那样工作。
我有BasicInputView
的子类,我们称它为CountryInputView
,它将SelectionInputControl<Country>
(在这种情况下Country
是enum
)对象放入rows
,但SelectionInputControl<Country>
都没有解析为SelectionInputControl<Any>
也不能使用SelectionInputControl
(因为它将无法编译)。
我该如何解决?任何帮助将不胜感激。
class BasicInputView: UIView {
var popoverPresenter: (UIViewController & UIPopoverPresentationControllerDelegate)? {
didSet {
for row in rows {
if let item = row as? SelectionInputControl<Any> {
item.popoverPresenter = popoverPresenter
}
}
}
}
private var rows = [BasicInputControl]()
}
class SelectionInputControl<T>: BasicInputControl {
var enumValues = [T]()
private var currentValue: T?
var popoverPresenter: (UIViewController & UIPopoverPresentationControllerDelegate)?
}
您无法将SelectionInputControl<Country>
强制转换为SelectionInputControl<Any>
,因为Swift中的泛型除了数组外没有其他变体。 :(
一种方法是引入另一个协议,PopoverPresentable
:
protocol PopoverPresentable {
var popoverPresenter: (UIViewController & UIPopoverPresentationControllerDelegate)? { get set }
}
使SelectionInputControl
符合此协议:
extension SelectionInputControl : PopoverPresentable {}
现在您可以强制转换为PopoverPresentable
:
if let item = row as? PopoverPresentable {
item.popoverPresenter = popoverPresenter
}