Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I report error when setting a swift property?

Tags:

swift

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?

like image 530
Michael Kennedy Avatar asked Dec 06 '25 09:12

Michael Kennedy


1 Answers

Options:

  1. Call fatalError which will crash the app
  2. Provide a default value if validation fails
  3. Don't change numberOfLegs if validation fails and log out an error message
  4. 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.

like image 163
drewag Avatar answered Dec 07 '25 22:12

drewag



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!