簡體   English   中英

如何在 Swift 中對關聯類型添加約束

[英]How to add constraint on associated type in Swift

我正在嘗試創建一個協議R ,其中包含一個對象數組n ,原則上,這些對象可以是不同的類( N1N2 ),但所有主題都屬於同一協議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]我不會改變NN1N2R

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM