Swift - didSetでgetter,setterがシンプルに
willSet, didSetをあまり使っていなかったが、使ってみたら便利だった話。
「currentIndexはgetできる」
「currentIndexはsetすると、その数字を内部で保持し、あるViewの色が変わる」
というようなものを、willSet, didSetを知らない間こんなふうに書いていました。
private var _currentIndex: Int = 0 var currentIndex: Int { get { return _currentIndex } set { _currentIndex = newValue view.backgroundColor = _currentIndex > 5 ? UIColor().redColor() : UIColor().blueColor() } }
ただこの書き方だと、currentIndexの役割をもったプロパティが2つできてしまい、
なんか心がもやもやします(恋かな?)
したらば、下の書き方にすると非常にシンプルに書くことができます。
var currentIndex: Int { didSet { view.backgroundColor = currentIndex > 5 ? UIColor().redColor() : UIColor().blueColor() } }
willSetはまだ使う機会ないのですが、さぞや活躍してくれることでしょう。むふふ