Data encapsulation in Swift

Posted by zpasternack on Stack Overflow See other posts from Stack Overflow or by zpasternack
Published on 2014-06-08T05:19:23Z Indexed on 2014/06/10 21:25 UTC
Read the original article Hit count: 259

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?

© Stack Overflow or respective owner

Related posts about encapsulation

Related posts about swift-language