Over a million developers have joined DZone.

Access Control in Swift

· Mobile Zone

Since Swift was released at WWDC this year, Apple have clearly stated the language is still in beta. This was proven by the fact that the last release, beta 4, introduced a new feature, "Access Control." Initially when Swift was released, this did seem like a glaring omission as almost every modern programming language today has some notion of Access Control.

3 levels

Swift has 3 levels of Access Control.

  1. private - Access from only the same file
  2. internal - Access from the same module
  3. public - Across modules

Let's start with private the most restrictive one. This will stop anybody accessing anything that is not in the same file.

For example, if I had a Person class with a name variable that wereprivate, nobody else outside the file would be able to access it.

So in Person.swift

class Person {  
    private let name: String

    init(name: String) {
        self.name = name
    }
}

And in main.swift

let person = Person(name: "John")  
println(person.name) // compile error  

Removing the private keyword from the variable, removes the compile error.

So again in Person.swift

class Person {  
    let name: String

    init(name: String) {
        self.name = name
    }
}

In main.swift

let person = Person(name: "John")  
println(person.name) // prints out John  

Internal

So when we removed the private keyword from our Person.swift class it had internal scope by default. This is the same as adding the internalkeyword to the attribute.

In Person.swift

class Person {  
    internal let name: String

    init(name: String) {
        self.name = name
    }
}

Public

Lastly, public should be used with modules and when exposing APIs. So if you want your functions/attributes to be accessible across modules, then use the public.

Summary

I hope you've learnt something about Swift's access controls in this post. Here are some references for further reading.

The source code for this post can be found herehttps://github.com/codingricky/Swift-Access-Control-Demo.

Topics:

Published at DZone with permission of Ricky Yim, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}