iCalvin.org

null_resettable Equivalent In Swift

Swift doesn’t have an annotation to indicate what in ObjC would be a null_resettable property. These are properties like UILabel.font, which never will return nil, but do allow you to set nil to reset to a default value.

In the past I’ve gotten around this by defining a get-only non-optional variable, and a function that acts as a setter which takes an optional. What I just learned from a coworker is that there’s a much better way to do this!

If you define your variable as an implicitly unwrapped type, in the set closure you can handle a nil case! So you can define a computed variable that resets to a default value when you define it as nil as such:

var foo: Bar! = .default {
  get {
    // Do some work to generate the variable here
  }
  set {
    var toSet: Bar = newValue ?? .default
    // Do whatever with the non-optional variable
  }
}

Hope this proves helpful to some of y’all! It makes me nervous as hell adding a bang to my Swift code, but this seems like one of those few times where it’s a great idea!

#swift #learning #woah