Reputation:
Imagine I need to write a Foobar
class with the following partial requirements:
someProperty
,SomeProperty
is an Integer with the following constraints:
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.
Upvotes: 3
Views: 907
Reputation: 11
In Switch statement flow, try adding the line:
default:
self.someProperty = oldValue
to preserve old valid state.
Upvotes: 1
Reputation: 5316
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
}
}
}
}
Upvotes: 4