3 回答

TA貢獻1807條經(jīng)驗 獲得超9個贊
解決您的更新用例:
(btw Printable已經(jīng)是標準的Swift協(xié)議,因此您可能希望選擇其他名稱以避免混淆)
要對協(xié)議實現(xiàn)者實施特定的限制,您可以限制協(xié)議的類型別名。因此,創(chuàng)建需要元素可打印的協(xié)議集合:
// because of how how collections are structured in the Swift std lib,
// you’d first need to create a PrintableGeneratorType, which would be
// a constrained version of GeneratorType
protocol PrintableGeneratorType: GeneratorType {
// require elements to be printable:
typealias Element: Printable
}
// then have the collection require a printable generator
protocol PrintableCollectionType: CollectionType {
typealias Generator: PrintableGenerator
}
現(xiàn)在,如果您想實現(xiàn)一個只能包含可打印元素的集合:
struct MyPrintableCollection<T: Printable>: PrintableCollectionType {
typealias Generator = IndexingGenerator<T>
// etc...
}
但是,這可能幾乎沒有什么實際用途,因為您不能像這樣約束現(xiàn)有的Swift集合結(jié)構(gòu),只能實現(xiàn)它們。
相反,您應該創(chuàng)建通用函數(shù),以將其輸入限制為包含可打印元素的集合。
func printCollection
<C: CollectionType where C.Generator.Element: Printable>
(source: C) {
for x in source {
x.print()
}
}
- 3 回答
- 0 關注
- 662 瀏覽
添加回答
舉報