Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 3 access of private properties in a struct from a extension

I've been looking through the swift docs and working through some examples around encapsulation, and am unsure about the behaviour that I'm seeing. I've looked for similar questions on stack, looked through the doc and looked through some tutorials (see the link below) and although this is a trivial question can't find an answer (possibly as Swift has changed?)

Creating a simple Struct representing a queue:

struct Queue<Element> {
private var elements = [Element]()
mutating func enqueue(newElement: Element) {
    elements.append(newElement)
}

mutating func dequeue() -> Element? {
    guard !elements.isEmpty else {
        return nil
    }
    return elements.remove(at: 0)
}
}

Is later extended by:

extension Queue {
func peek() -> Element? {
    return elements.first
}
}

But of course elements is inaccessible due to the private protection level. It works by changing the access of elements to fileprivate - but why?

My understanding was that extensions were part of the enclosing type, and looking around the web it seems that is used to work this way https://www.andrewcbancroft.com/2015/04/22/3-nuances-of-swift-extensions/

So is my understanding of visibility wrong, or has Swift changed?

like image 200
stevenpcurtis Avatar asked Mar 01 '17 02:03

stevenpcurtis


2 Answers

From the Swift's book:

Private access restricts the use of an entity to the enclosing declaration. Use private access to hide the implementation details of a specific piece of functionality when those details are used only within a single declaration.

So a private variable is only accessible within the set of curly brackets where it's defined. Swift's Access Control has never been like those of C++ , Java or C#.

like image 75
Code Different Avatar answered Oct 10 '22 11:10

Code Different


With release of Swift 4 this has been changed if the extension is implemented within the same file. You can refer the doc here Private Member in Extension

Example below is from Swift 4

protocol SomeProtocol {
    func doSomething()
}
struct SomeStruct {
    private var privateVariable = 12
}
extension SomeStruct: SomeProtocol {
    func doSomething() {
        print(privateVariable)
    }
}
like image 3
manismku Avatar answered Oct 10 '22 12:10

manismku