11

It seems that there is not a private, or for that matter public, keyword in swift language. So it is possible at all to have a private property?

On a side note, Swift is very much similar to Typescript per my observation so far.

67cherries
  • 6,931
  • 7
  • 35
  • 51
Sean Dong
  • 575
  • 9
  • 16

1 Answers1

24

Update:

As of Xcode 6 beta 4, Swift has Access Control - https://developer.apple.com/swift/blog/?id=5


Swift doesn't have access modifiers yet. But there are plans to add them in the future

There are also some workarounds mentioned in the above linked thread, like using nested classes:

import Foundation

class KSPoint {

    /*!
     * Inner class to hide the helper functions from codesense.
     */
    class _KSPointInner {
        class func distance(point p1 : KSPoint, toPoint p2 : KSPoint) -> Double {
            return sqrt(pow(Double(p2.x - p1.x), 2) + pow(Double(p2.y - p1.y), 2))
        }
    }

    var x : Int

    var y : Int

    init(x : Int = 0, y : Int = 0) {
        self.x = x
        self.y = y
    }

    func distance(point : KSPoint, toPoint : KSPoint) -> Double {
        return _KSPointInner.distance(point: point, toPoint: toPoint)
    }
}
manojlds
  • 290,304
  • 63
  • 469
  • 417
  • 17
    Who down-votes the truth just because it's unpleasant? – IluTov Jun 03 '14 at 18:02
  • As you mention, nested classes are only workarounds. IMO, better to use protocols and factories, or to prefix private and protected members and wait for the promised access modifiers. – Gregzo Jun 04 '14 at 10:20
  • I downvoted because at first all the answer said was "Swift doesn't have access modifiers yet. But there are plans to add them in the future", with no evidence or explaining details. @NSAddict – John Riselvato Jun 04 '14 at 14:39
  • Like Javascript, one could use closures as a pretty solid way to achieve privacy. – mxcl Jun 05 '14 at 00:21
  • @JohnRiselvato There was no work-a-round code sample, but already when you downvoted there was link to the Apple discussion forum and on this form an Apple employee literally promises that there **will be** access modifiers. How is that not an evidence? – Mecki Jun 12 '14 at 11:35
  • because at the time of my comment, @Mecki, there was no url to this discussion. – John Riselvato Jun 12 '14 at 14:16
  • @JohnRiselvato Look at the history. The link was there. – IluTov Jun 15 '14 at 11:53