はじめに
私は最近、拡張の便利さに気づいて使いまくってます
パターンがいくつか合ったので適切に使えるように整理しておきます。
パターン1
個人的に見た目が悪いから好きじゃない
でも、一番使い方が簡単な気がする
関数部分で引数を取らないならパターン2を使うべきかな
型変換可能
extension Int {
func square() -> Int {
return self * self
}
}
print(5.squared()) // 25
パターン2
パターン1と似てる
後ろの()
がない分見た目はまし
型変換可能
extension Int {
var square: Int {
return self * self
}
}
print(5.squared) // 25
パターン3
これは見た目がいい
おそらく型変換は不可
extension Int {
init(square: Int) {
self.init(square * square)
}
}
print(Int(square: 5)) // 25
おわり
使いこなせたらつよつよになれそう