On Sep 6, 2016, at 21:31 , Gerriet M. Denkmann <[email protected]> wrote:
>
> My Swift book (2.2) has no mention of “private” (Swift 3 beta has).
It’s in the 2.2 book under “Language Guide” section “Access Control"
> But even assuming I had Swift 3, I do not quite understand how this should be
> done (I may be a bit dense).
It’s a bit of syntactical pseudo-magic, but it makes sense when you think about
it.
If you have (say) an instance property:
class X {
var x: int
}
then property x is both gettable and settable by clients of the class. If you
declare it private:
class X {
private var x: int
}
then (like Obj-C) the property is private and can only be used inside the
class. But you can declare just the setter to be private, using this syntax:
class X {
private(set) var x: int
}
In that case, you can freely change the value inside the class, but to clients
of the class, it "looks like" the property is declared like this:
class X {
let x: int
}
The Obj-C analog is to declare the property ‘readonly’ in the public interface
in the .h file, and ‘readwrite’ in a private interface extension inside the .m
file.
This use of ‘private(set)’ doesn’t prevent you from accidentally changing the
value inside the class somewhere. If you want to do that, you’re going to have
to get a bit more exotic, maybe a ‘lazy’ let.
In Swift 2, “private” actually means “accessible by everything in the same
source file”. In Swift 3, that’s renamed to “fileprivate”, and “private” means
“accessible only within the declaring class/struct”.
_______________________________________________
Cocoa-dev mailing list ([email protected])
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com
This email sent to [email protected]