Search code examples
encapsulationswift

Data encapsulation in Swift


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?


Solution

  • It's simply missing at the moment. Greg Parker has explicitly stated (in this dev forums thread) that visibility modifiers are coming.

    Given that there aren't headers, the standard Objective-C tricks won't work, and I can't think of another trick to limit visibility that doesn't involve lots of bending over backwards. Since the language feature has been promised I'm not sure it's worth any big investment.

    On the bright side since this feature is in flux, now is a great time to file a radar and influence how it turns out.