user1040049
user1040049

Reputation:

Encapsulating property transformation/validation

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

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

Answers (2)

Enigma
Enigma

Reputation: 11

In Switch statement flow, try adding the line:

default: 
  self.someProperty = oldValue 

to preserve old valid state.

Upvotes: 1

Analog File
Analog File

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

Related Questions