[swift-evolution] [Review] SE-0169: Improve Interaction Between private Declarations and Extensions
Nevin Brackett-Rozinsky
nevin.brackettrozinsky at gmail.com
Mon Apr 17 16:46:13 CDT 2017
On Mon, Apr 17, 2017 at 4:52 PM, Tino Heth <2th at gmx.de> 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
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170417/2e082721/attachment.html>
More information about the swift-evolution
mailing list