How to conform to a protocol's variables' set & get?

前端 未结 2 1218
谎友^
谎友^ 2021-02-18 23:30

I\'m playing around with protocols and how to conform to them.

protocol Human {    
    var height: Int { get set }    
}

struct Boy: Human { 
    var height: In         


        
2条回答
  •  甜味超标
    2021-02-19 00:07

    From the Swift Reference:

    Property Requirements

    ...
    The protocol doesn’t specify whether the property should be a stored property or a computed property—it only specifies the required property name and type.
    ...
    Property requirements are always declared as variable properties, prefixed with the var keyword. Gettable and settable properties are indicated by writing { get set } after their type declaration, and gettable properties are indicated by writing { get }.

    In your case

    var height: Int  {return 5} // error!
    

    is a computed property which can only be get, it is a shortcut for

    var height: Int {
        get {
            return 5
        }
    }
    

    But the Human protocol requires a property which is gettable and settable. You can either conform with a stored variable property (as you noticed):

    struct Boy: Human { 
        var height = 5
    }
    

    or with a computed property which has both getter and setter:

    struct Boy: Human { 
        var height: Int {
            get {
                return 5
            }
            set(newValue) {
                // ... do whatever is appropriate ...
            }
        }
    }
    

提交回复
热议问题