2017-05-22 23 views
2

我正在寫一個有readOnly標籤的協議。我想擴展它,並在符合類型爲UITextView的情況下給它一個默認實現。如何使用專用設置擴展協議?

代碼:

protocol CountingView { 

    var keyboardLabel : UILabel {get} 
} 

extension CountingView where Self : UITextView { 

    var keyboardLabel : UILabel { 
     get { 
      let label = UILabel() 
      label.textColor = UIColor.white 
      label.translatesAutoresizingMaskIntoConstraints = false 

      return label 
     } 
     private (set) { 
     keyboardLabel = newValue 
     } 
    } 
} 

然而,當我在set我收到以下錯誤前添加private

預計「獲得」,「設置」,「willSet」或「didSet」關鍵字來啓動 訪問定義

我擡頭等問題,與此錯誤,但沒有找到他們與我的相關。

+2

擴展*不能*添加存儲性能。你的二傳手會遞歸地調用它自己。比較https://stackoverflow.com/questions/44063181/protocol-extension-in-swift-3。 –

+0

@MartinR ummm。好。你的意思是這裏的答案不正確? – Honey

+0

那麼,你的*問題*是如何使'private(set)'* compile。*答案似乎是正確的。我的觀點是,即使你編譯它,你設置的'keyboardLabel = newValue'的*實現*也不會按預期工作。 –

回答

4

你只是有私人在錯誤的地方:

private(set) var keyboardLabel : UILabel { 
    get { 
     let label = UILabel() 
     label.textColor = UIColor.white 
     label.translatesAutoresizingMaskIntoConstraints = false 

     return label 
    } 
    set { 
     keyboardLabel = newValue 
    } 
} 
0

只要讓你的計算性能private就象這樣:

public private(set) var keyboardLabel : UILabel { 
    get { 
     let label = UILabel() 
     label.textColor = UIColor.white 
     label.translatesAutoresizingMaskIntoConstraints = false 

     return label 
    } 

    set { 
     keyboardLabel = newValue 
    } 
}