[英]How to add constraint on associated type in Swift
我正在嘗試創建一個協議R
,其中包含一個對象數組n
,原則上,這些對象可以是不同的類( N1
, N2
),但所有主題都屬於同一協議N
。 提交給協議R
( M1
, M2
) 的類可以決定它們的屬性數組n
是否只包含特定種類的R
或任何。
這編譯得很好:
protocol N { }
class N1: N { }
class N2: N { }
protocol R {
associatedtype NType
var n: [NType] { get set }
}
class M1: R {
var n: [N] = [N1(), N2()]
}
class M2: R {
var n: [N1] = [N1(), N1()]
}
但是我不明白如何向它必須符合N
的關聯Ntype
添加約束。 在行的東西
protocol N { }
class N1: N { }
class N2: N { }
protocol R {
associatedtype NType: N
var n: [NType] { get set }
}
class M1: R {
var n: [N] = [N1(), N2()]
}
class M2: R {
var n: [N1] = [N1(), N1()]
}
這不會編譯說Type 'M1' does not conform to protocol 'R'
。
使用 swift 5.7.1 你可以使用[any N]
我不會改變N
, N1
, N2
或R
:
protocol N { }
class N1: N { }
class N2: N { }
protocol R {
associatedtype NType
var n: [NType] { get set }
}
但是我會使用和any N
的數組以不同的方式實現M1
,例如:
class M1: R {
var n: [any N] = [N1(), N2()]
}
編譯並打印:
let m1 = M1()
print(m1.n) // [__lldb_expr_13.N1, __lldb_expr_13.N2]
m1.n.append(N2()) // [N1, N2, N2]
m1.n.append(N1()) // [N1, N2, N2, N1]
但它也可以容納特定種類的N
,例如:
class M2: R {
var n: [N1] = [N1(), N1()]
}
輸出:
let m2 = M2()
print(m2.n) // [__lldb_expr_17.N1, __lldb_expr_17.N1]
m2.n.append(N1()) // [N1, N1, N1]
m2.n.append(N2()) // No exact matches in call to instance method 'append'
如您所見, m1.n
是一個符合NType
aka N
的異構對象數組,而m2.n
只能保存N1
個值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.