Obj-Cの@property (nonatomic) NSArray <SomeProtocol>* items;
をミラーリングする最善の方法は、項目がUIView
のサブクラスです。以下の例ではプロトコルに準拠した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]?
}
おそらくこの記事は助けになるかもしれません:https://milen.me/writings/swift-generic-protocols/ – nebs
あなたのプロトコルを ':class'として宣言する必要があります。構造体ではなくオブジェクト – Paulw11