コードリーディングをしていた時に見つけたコード。
public internal(set) var appName: String?
SwiftではGetterとSetterで異なるアクセス修飾子を設定出来るみたい。
上のコードは、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)
どうやらSetterにはGetterよりも低いアクセスレベルを割り当てることが出来るみたい。
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
に値を入れようとするとエラーが発生する。