On Mon, Apr 17, 2017 at 4:52 PM, Tino Heth <[email protected]> wrote:
>
> the only way to hide one invariant from the other’s methods is to use
> helper types
>
> Could you elaborate here and give an example that uses such helper types?
>
Okay, let’s say we have a type Foo with a String property and an Int
property. The invariants we’ll preserve are that the String must begin with
“secret ” and the Int must be divisible by 3.
struct Foo {
private var secretString = SecretString()
private var divisibleBy3 = MultipleOfThree()
var x: Int {
get { return divisibleBy3.value }
set { divisibleBy3.update(newValue) }
}
var y: String {
get { return secretString.value }
set { secretString.update(newValue) }
}
// rest of the implementation
}
private struct MultipleOfThree {
private(set) var value: Int = 0
mutating func update(_ n: Int) { value = 3 * n }
}
private struct SecretString {
private(set) var value: String = "secret value"
mutating func update(_ s: String) { value = "secret " + s }
}
Now the only places that the invariants could possibly be broken are inside
the helper types themselves. Anything within the implementation of Foo can
call the “update” functions, but cannot directly alter the values inside
the helper types and so cannot violate the invariants. Thus, with this
pattern, to confirm that the invariants are preserved we need only look at
the helper types, which are short and self-contained.
Nevin
_______________________________________________
swift-evolution mailing list
[email protected]
https://lists.swift.org/mailman/listinfo/swift-evolution