Data encapsulation in Swift
- by zpasternack
I've read the entire Swift book, and watched all the WWDC videos (all of which I heartily recommend). One thing I'm worried about is data encapsulation.
Consider the following (entirely contrived) example:
class Stack<T>
{
var items : T[] = []
func push( newItem: T ) {
items.insert( newItem, atIndex: 0 )
}
func pop() -> T? {
if items.count == 0 {
return nil;
}
return items.removeAtIndex( 0 );
}
}
This class implements a stack, and implements it using an Array. Problem is, items (like all properties in Swift) is public, so nothing is preventing anyone from directly accessing (or even mutating) it separate from the public API. As a curmudgeonly old C++ guy, this makes me very grumpy.
I see people bemoaning the lack of access modifiers, and while I agree they would directly address the issue (and I hear rumors that they might be implemented Soon (TM) ), I wonder what some strategies for data hiding would be in their absence.
Have I missed something, or is this simply an omission in the language?