【发布时间】:2016-11-19 00:32:45
【问题描述】:
镜像 Obj-C 的 @property (nonatomic) NSArray <SomeProtocol>* items; 的最佳方式是什么,其中项目是 UIView 子类?
在下面的示例中,我想存储一个 UIKit 组件数组(例如 UILabel、UIButton 等),它们都符合协议,但这会产生错误 Protocol can only be used as a generic constraint because it has Self or associated type requirements
有哪些其他的建模方法?
示例游乐场:
import UIKit
/// Protocol representing a form field model
protocol FieldRepresentable {}
/// Protocol representing a form UI control
protocol FormControllable {
associatedtype FieldRepresentable
init(model: FieldRepresentable)
var model: FieldRepresentable { get }
}
/// Example label model
class FormLabelElement: FieldRepresentable {}
/// Example label UI control
class FormLabel: UILabel, FormControllable {
required init(model: FormLabelElement) {
self.model = model
super.init(frame: CGRect.zero)
}
let model: FormLabelElement
required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") }
}
/// Example form
class Form: UIView {
// Error here
var fields: [FormControllable]?
}
【问题讨论】:
-
或许这篇文章能有所帮助:milen.me/writings/swift-generic-protocols
-
您需要将您的协议声明为
:class以表明它只适用于类对象,而不适用于结构
标签: ios swift generics swift3 protocols