-2

here is my code in swift ,what is the problem,i just want to use computed property with static keyword.

class TypeProperty {
  static var Info:String {
    set(str) {
      TypeProperty.Info = str
    }
    get { 
     return "none"
    }
  }
}
TypeProperty.Info = "I am Info" /* here i get error ,what is problem with it */ 
Hamish
  • 78,605
  • 19
  • 187
  • 280
  • What error? Runtime or compile-time? Your code won't work because saying `TypeProperty.Info = str` inside the setter just calls the setter recursively. Although what's the point in having a setter if the getter is just going to always return `"none"`? – Hamish May 22 '17 at 09:17

1 Answers1

0

Problem is whenever you set Info TypeProperty.Info = "I am Info" it will stuck in an infinite loop. It's because you are setting same variable within the setter of that variable.

You can do something like that..

class TypeProperty {
    static var _info:String?
    static var Info:String {
        set(str) {
            _info = str
        }
        get {
            return _info ?? "none"
        }
    }
}
Bilal
  • 18,478
  • 8
  • 57
  • 72
  • It is mean when i use " = " assign new value for computed property(not stored property ) , the swift will automatically call the setter method for the computed property ? If that , I think i can understand what you say about the “ it will stuck in an infinite loop. ” – beyondbycyx May 22 '17 at 10:17
  • Yes when you use `=` operator followed by any string it will trigger the setter (`set`) – Bilal May 22 '17 at 10:19