Ch. 26, Property Wrapper, Bronze Challenge

Bronze challenge, my solution (please review my code):

@propertyWrapper struct Logged {
  
  private var storage: Int
  
  var wrappedValue: Int {
    get {
      return storage
    }
    set {
      
      if newValue < warningValue {
        let result = max(newValue, 0)
        print("Warning!!! New value \(result) is lower than warningValue: \(warningValue)")
      } else {
        print("Population changed, old value: \(storage), newValue: \(newValue)")
      }
      
      storage = max(newValue, 0)
    }
  }
  var warningValue: Int
  
  init(wrappedValue: Int, warningValue: Int) {
    storage = wrappedValue
    self.warningValue = warningValue
  }
}


I made mine slightly more generic with a description property for the log message.

@propertyWrapper public struct Logged {
    private var storage: Int
    private var warningValue: Int
    private var description: String
    
    public init(wrappedValue: Int, warningValue: Int = 0, description: String = "") {
        storage = wrappedValue
        self.warningValue = warningValue
        self.description = description
    }
    
    public var wrappedValue: Int {
        set {
            if newValue != storage {
                print("\(description) changed from \(storage) to \(newValue)")
            }
            if newValue < warningValue {
                print("\(description) is getting too low")
            }
            storage = newValue
        }
        get {
            return storage
        }
    }
}

In Town:

    @Logged(warningValue: 50, description: "Town population") var population: Int = 1

produces:

Town population changed from 100 to 40
Town population is getting too low

1 Like