0
2

More than 1 year has passed since last update.

【Swift】extensionのパターン

Last updated at Posted at 2022-05-21

はじめに

私は最近、拡張の便利さに気づいて使いまくってます
パターンがいくつか合ったので適切に使えるように整理しておきます。

パターン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

おわり

使いこなせたらつよつよになれそう

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2