Basic Example using a Struct
suggest changeIn 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 works everywhere, including in targets that import the module that defines 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: String) {
self.make = make
self.model = model
self.fullName = "\(make)\(model)"
}
}
When members of a type have different access levels, each member keeps its own level. A private property of a public type is still private.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents