Given that Swift does not have exception handling how do I communicate errors back to the caller when they pass an incorrect value for a property. Essentially, can properties have validation?
Here is an example. Consider numberOfShoes property below. It's computed
class Animal {
var name : String
var numberOfLegs : Int
var numberOfShoes : Int {
get {return numberOfLegs }
set {
if newValue < 0 {
// TODO: WHAT GOES HERE?
}
numberOfLegs = newValue
}
}
init(name : String, numberOfLegs : Int) {
self.name = name
self.numberOfLegs = numberOfLegs
}
}
We could (should maybe) also have a willSet / didSet observer on numberOfLegs but I don't see how validation can be done here either.
Are we required to stick with things like:
var cat = Animal("Cat", 4)
if !cat.setNumberOfLegs(3) {
// I guess that didn't work...
}
What is everyone else doing?
Options:
Make numberOfShoes read only and instead provide a function to set the number of shoes that returns an optional error:
func setNumberOfShoes(number: Int) -> NSError? { // ... }
Option 4 is the closest to an exception in that it allows the calling code to decide how it want to handle the invalid input. Of course, it does not however, force the caller to handle the error.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With