How do I report an error while setting a Quick property?

Given that Swift has no exception handling, how do I pass errors back to the caller when they pass the wrong value for a property. Essentially, can the properties be checked?

Here's an example. Consider the numberOfShoes property . He calculated

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) also have a willSet / didSet observer on numberOfLegs, but I don't see how the validation can be done here.

Should we stick with things like:

var cat = Animal("Cat", 4)
if !cat.setNumberOfLegs(3) {
   // I guess that didn't work...
}

      

What are the others doing?

+3


source to share


2 answers


Parameters:

  • Calling fatalError that will crash the application
  • Provide default value if validation fails
  • Do not change numberOfLegs if validation fails and logged out error message
  • Make numberOfShoes read-only and instead provide a function to set the number of shoes that return an additional error:

    func setNumberOfShoes (number: Int) -> NSError? {// ...}



Option 4 is the closest thing to an exception because it allows the caller to decide how it wants to handle invalid input. Of course, it does not, however, force the caller to handle the error.

+5


source


In Swift 2, you have a partial solution using a setter function and error handling:

class Animal {

    enum Error: ErrorType {
        case Invalid
    }

    var name : String
    var numberOfLegs : Int
    var numberOfShoes : Int {
        get {return numberOfLegs }
    }

    func setNumberOfShoes(n: Int) throws {
        if n < 0 {
            throw Error.Invalid
        }
        self.numberOfLegs = n
    }
    init(name : String, numberOfLegs : Int) {
        self.name = name
        self.numberOfLegs = numberOfLegs
    }
}

var cat = Animal(name: "Cat", numberOfLegs: 4)
do {
    try cat.setNumberOfShoes(0)
    print("0 shoes is ok for an animal")
    try cat.setNumberOfShoes(-1)
} catch Animal.Error.Invalid {
    print("but -1 is not")
}

      



Ultimately, swift will support declaring a computed property that it "throws" .

0


source







All Articles