Basic Example using a Struct

suggest change

In Swift 3 there are multiple access-levels. This example uses them all except for open:

public struct Car {
    
    public let make: String
    let model: String //Optional keyword: will automatically be "internal"
    private let fullName: String
    fileprivate var otherName: String
    
    public init(_ make: String, model: String) {
        self.make = make
        self.model = model
        self.fullName = "\(make)\(model)"
        self.otherName = "\(model) - \(make)"
    }
}

Assume myCar was initialized like this:

let myCar = Car("Apple", model: "iCar")

Car.make (public)

print(myCar.make)

This print will work everywhere, including targets that import Car.

Car.model (internal)

print(myCar.model)

This will compile if the code is in the same target as Car.

Car.otherName (fileprivate)

print(myCar.otherName)

This will only work if the code is in the same file as Car.

Car.fullName (private)

print(myCar.fullName)

This won’t work in Swift 3. private properties can only be accessed within the same struct/class.

public struct Car {

    public let make: String       //public
    let model: String             //internal
    private let fullName: String! //private 

    public init(_ make: String, model model: String) {
        self.make = make
        self.model = model
        self.fullName = "\(make)\(model)"
    }
}

If the entity has multiple associated access levels, Swift looks for the lowest level of access. If a private variable exists in a public class, the variable will still be considered private.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents