3

Imagine I need to write a Foobar class with the following partial requirements:

  • it needs a read-write property called someProperty,
  • SomeProperty is an Integer with the following constraints:
    • Value must be within 0 to a 100 (inclusively).
    • 42 is an invalid value; If 42 is supplied for SomeProperty the next valid value (43) will be used/stored.

How would this be accomplished in Swift?

class Foobar {
    var someProperty: Int = 0 {
        get {
            return someProperty
        }
        set {
            switch newValue {
            case 42:
                someProperty = 43
            case 0...100:
                someProperty = newValue
            default:
                someProperty = 0
            }
        }
    }
}

According to Property getters and setters , this is an incorrect use of setters. If so, how would it be coded? I don't want every calling entity having to validate Foobar. Foobar should validate itself (promoting encapsulation).

foobarObject.someProperty = 42     // This is wrong, 42 is an invalid value, but how would Foobar enforce this?
println(foobarObject.someProperty) // Should print `43`, because 42 is invalid and it would use the next valid number

I've toyed a bit with the idea of having didSet or willSet do the validation but somehow this seems like a cludge.

Community
  • 1
  • 1

2 Answers2

4

Try this

class Foobar {
    var someProperty: Int = 0 {
        didSet {
            switch self.someProperty {
            case 42:
                self.someProperty = 43
            case 0...100:
                break;
            default:
                self.someProperty = 0
            }
        }
    }
}
Analog File
  • 5,280
  • 20
  • 23
1

In Switch statement flow, try adding the line:

default: 
  self.someProperty = oldValue 

to preserve old valid state.

ZeMoon
  • 20,054
  • 5
  • 57
  • 98
Enigma
  • 11
  • 2