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")
print(myCar.make)
This print will work everywhere, including targets that import Car
.
print(myCar.model)
This will compile if the code is in the same target as Car
.
print(myCar.otherName)
This will only work if the code is in the same file as Car
.
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.