How to create a custom getter method in swift 4

為{幸葍}努か 提交于 2019-12-19 11:05:48

问题


I am trying to create a custom setter method for my property. Below is my code.

I am getting a waring Attempting to access 'myProperty' within its own getter

var myProperty:String{
    get {

        if CONDITION1 {
            return CONDITION1_STRING
        }else if CONDITION2 {
            return CONDITION2_STRING
        }else{
            return myProperty
        }

    }

    set{

    }
}

What is wrong in my code. can any body help to fix this.


回答1:


Create a backing ivar and add a custom setter:

private _myProperty: String 
var myProperty: String {
    get {
        if CONDITION1 {
            return CONDITION1_STRING
        } else if CONDITION2 {
            return CONDITION2_STRING
        } else {
            return _myProperty
        }
    }
    set {
        _myProperty = newValue
    }
}



回答2:


First of all quote from Apple Swift Documentation:

Computed Properties

In addition to stored properties, classes, structures, and enumerations can define computed properties, which do not actually store a value. Instead, they provide a getter and an optional setter to retrieve and set other properties and values indirectly.

The first thing above quote suggesting is that, you can use custom getter and setter of property to get or set values of other property indirectly without exposing it or make it public for others.

If you try to access/get value of property within its own getter than again you are calling getter and loops go infinite. As we know allocation of all this calls are on stack, and stack has limited memory, so once calls stacked at full capacity then it can not handle any more calls and it crash with stackoverflow error.

So, never get or set property's value within its own getter and setter. They are here to provide access to other variables and properties.

Lets expand your code to use myProperty With custom getter. I am renaming it here it as myName.

private var firstName : String = ""
private var lastName : String = ""

var myName:String{
    get {

        if CONDITION1 {
            return firstName
        }else if CONDITION2 {
            return lastName
        }else{
            return firstName + lastName
        }
    }
}

Here I add two private property firstName and lastName but make it private. But I add another property myName which is public, so i implement custom getter to retrieve name of user based on condition and provide access of firstName and lastName indirectly.

By same way you can implement custom setter to set value of firstName and lastName of user. But you can not make use of self within its own scope.



来源:https://stackoverflow.com/questions/49148782/how-to-create-a-custom-getter-method-in-swift-4

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