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

删除回忆录丶 提交于 2019-12-06 19:01:13

问题


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

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

struct boy : Human { 
    var height: Int  {return 5} // error!
}

I'm trying to learn different ways that I can implement set and get. However the code above throws the following error:

type 'boy' does not conform to protocol 'Human'

However writing as below won't have any errors:

struct boy : Human { 
    var height = 5 // no error
}

I don't understand the difference nor what exactly needs to be implemented when you can also set a variable. I looked into different questions and tutorials but they all just write and go without any deeper explanation.

EDIT: make sure you see Imanou's answer here. It greatly explains the different scenarios.


回答1:


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 ...
        }
    }
}



回答2:


Prerequisite:

Go into your playground and just write the snippet below:

var height: Int {
    get {
        return 5
    }
}    

or similarly:

var height: Int {
    return 5
}    

Try to print height's value, obviously works. So far so good

print(height) // prints 5

However if you try to set it to a new value then you'll get an error:

height = 8 // ERROR  

error: cannot assign to value: 'height' is a get-only property


Answer:

Based on Martin's answer, I first wrote:

set(newValue) {
    height = newValue 
}

Which put a ton of load on my memory and led me to this question. Please take a look. So then I was figuring out what to write, and I kind of understood that if you don't want to do anything special you shouldn't be using computed properties and instead you should just use normal stored properties.

So I wrote a similar code

protocol Human {

    var height: Float {get set}

}

struct Boy: Human {

    // inch
    var USheight : Float

    // cm
    var height: Float {
        get {
            return 2.54 * USheight
        }
        set(newValue) {
         USheight = newValue/2.54

        }
    }
}

// 5 ft person
var person = Boy(USheight: 60)
 // interestingly the initializer is 'only' based on stored properties because they
 // initialize computed properties. 


// equals to 152cm person
print(person.height) // 152.4

Pro tip: When should you should make your properties read-only?

Normally if you make a property to be read-only ie { get } it's because those properties are computed and you don't want the object to have control over it.

Example you have a JSON object. It has multiple big objects like:

JSONData
 - userInfo (name, address, age)
 - devices (iPads, iPhones, Mac books)
 - credentials (basic iCloud, pro iCloud, celebrity)

by making the role a read-only you're only allowing the server to tell the code base the role of the user.

protocol Credentials {
    var role: String { get }

    init(person: Person)
}

class Person {
    var userInfo: String
    var devices: [String]
    var creds: Credentials {
        Credentials(person: self)
    }

    init(userInfo: userInfo, devices: [String]) {
        self.userInfo = userInfo
        self.devices = devices
    }
}


来源:https://stackoverflow.com/questions/40820913/how-to-conform-to-a-protocols-variables-set-get

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!