[Swift] GetterとSetterには異なるアクセス修飾子を設定できる


public internal(set) var appName: String?

上のコードは、getterはpublic, setterはinternalと別々の修飾子が付いている。


internal var appName: String?

public func getAppName() -> String? {
    return appName

Getters and setters for constants, variables, properties, and subscripts automatically receive the same access level as the constant, variable, property, or subscript they belong to.
You can give a setter a lower access level than its corresponding getter, to restrict the read-write scope of that variable, property, or subscript. You assign a lower access level by writing fileprivate(set), private(set), or internal(set) before the var or subscript introducer.
The Swift Programming Language (Swift 4.1)

internal(set) private(set) fileprivate(set)といったアクセス修飾子が用意されている。

struct TrackedString {
    private(set) var numberOfEdits = 0
    var value: String = "" {
        didSet {
            numberOfEdits += 1

var stringToEdit = TrackedString()
stringToEdit.value = "This string will be tracked."
stringToEdit.value += " This edit will increment numberOfEdits."
stringToEdit.value += " So will this one."
print("The number of edits is \(stringToEdit.numberOfEdits)")
// Prints "The number of edits is 3"
stringToEdit.numberOfEdits = 10
// error: Cannot assign to property: 'numberOfEdits' setter is inaccessible

private(set) の為、 stringToEdit に値を入れようとするとエラーが発生する。