我正在玩弄協議以及如何遵守協議。如何符合協議變量的set&get?
protocol Human {
var height: Int {get set}
}
struct boy : Human {
var height: Int {return 5} // error!
}
我想學習不同的方法,我可以實現設置和獲取。 但是上面的代碼引發以下錯誤:
type 'boy' does not conform to protocol 'Human'
但是寫如下不會有任何錯誤:
struct boy : Human {
var height = 5 // no error
}
我不理解上的差異,也正是需要被實施時什麼你也可以設置一個變量。我研究了不同的問題和教程,但他們都只是寫下去,沒有更深入的解釋。
FWIW'結構男孩:人類{ 設高度= 5 //錯誤! '也會產生一個錯誤。原因在[this]中提及(Martin https://stackoverflow.com/questions/40820913/how-can-you-conform-protocol-variables-set-get/40820968?noredirect=1#comment85239656_40820968)。 *'var'聲明一個變量,'let'一個常量。作爲存儲屬性,第一個是讀/寫,第二個只讀* – Honey