亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何將通用協議用作變量類型

如何將通用協議用作變量類型

浮云間 2019-11-25 15:49:27
假設我有一個協議:public protocol Printable {    typealias T    func Print(val:T)}這是實現class Printer<T> : Printable {    func Print(val: T) {        println(val)    }}我的期望是我必須能夠使用Printable變量來打印這樣的值:let p:Printable = Printer<Int>()p.Print(67)編譯器抱怨此錯誤:“協議'Printable'只能用作一般約束,因為它具有Self或相關的類型要求”難道我做錯了什么 ?有任何解決這個問題的方法嗎 ?**EDIT :** Adding similar code that works in C#public interface IPrintable<T> {    void Print(T val);}public class Printer<T> : IPrintable<T>{   public void Print(T val)   {      Console.WriteLine(val);   }}//.... inside Main.....IPrintable<int> p = new Printer<int>();p.Print(67)編輯2:我想要的真實世界的例子。請注意,這不會編譯,但會介紹我想要實現的目標。protocol Printable {   func Print()}protocol CollectionType<T where T:Printable> : SequenceType {   .....   /// here goes implementation   ..... }public class Collection<T where T:Printable> : CollectionType<T>{    ......}let col:CollectionType<Int> = SomeFunctiionThatReturnsIntCollection()for item in col {   item.Print()}
查看完整描述

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()

        }

}


查看完整回答
反對 回復 2019-11-25
  • 3 回答
  • 0 關注
  • 657 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號