Swift の Read-Only Computed Properties
Swift製のオープンソースを眺めているとこういう文法を見ることがある。
class MyClass {
var a:Int = 1
var b:Int = 2 var myComputedValue : Int {
return a + b
}
}
myComputedValue
は a+b
を返すんだろうけど、中途半端な関数のように見える。
正体は Read-Only Computed Properties
この書き方の正体は The Swift Programming Language (Swift 4): Properties Read-Only Computed Properties に記載があった。
Read-Only Computed Properties A computed property with a getter but no setter is known as a read-only computed property. A read-only computed property always returns a value, and can be accessed through dot syntax, but cannot be set to a different value.
The Swift Programming Language (Swift 4): Properties
You can simplify the declaration of a read-only computed property by removing the get keyword and its braces:
Read-Only Computed Properties では get
は省略可能なのだ。
上の例はこう書いたのと同じである。
class MyClass {
var a:Int = 1
var b:Int = 2 var myComputedValue : Int {
get{
return a + b
}
}
}
ちなみに Computed Properties
SwiftのComputed Properties は 見た目はプロパティで値が保持されているように見えるが、実際は動的に計算されて値が返ってきたり、セット時に処理を加えることができるプロパティ。普通に.(ピリオド)でアクセスできる。 上の例では myComputedValue は こんなふうに利用できる。
let my = MyClass()
print(my.myComputedValue)
後記
モダン言語記法にちっとも慣れないので、脳に印字するために記載。