3 回答

TA貢獻1807條經驗 獲得超9個贊
解決您的更新用例:
(btw Printable已經是標準的Swift協議,因此您可能希望選擇其他名稱以避免混淆)
要對協議實現者實施特定的限制,您可以限制協議的類型別名。因此,創建需要元素可打印的協議集合:
// 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
}
現在,如果您想實現一個只能包含可打印元素的集合:
struct MyPrintableCollection<T: Printable>: PrintableCollectionType {
typealias Generator = IndexingGenerator<T>
// etc...
}
但是,這可能幾乎沒有什么實際用途,因為您不能像這樣約束現有的Swift集合結構,只能實現它們。
相反,您應該創建通用函數,以將其輸入限制為包含可打印元素的集合。
func printCollection
<C: CollectionType where C.Generator.Element: Printable>
(source: C) {
for x in source {
x.print()
}
}
- 3 回答
- 0 關注
- 657 瀏覽
添加回答
舉報