LoginSignup
62
61

More than 5 years have passed since last update.

インスタンスメソッド内でクラスメソッドを呼ぶ #Swift

Last updated at Posted at 2014-06-05

Objective-Cでいうところの [[self class] classMethod] を Swift では以下のように書くことが出来るようです。

class Hoge {
    class func classMethod() {
        println("classMethod")
    }

    func method() {
        self.dynamicType.classMethod()
    }
}

let hoge = Hoge()
hoge.method() // "classMethod"
hoge.dynamicType.classMethod() // "classMethod"

dynamicTypeを使うと、インスタンスのクラス自身(サブクラス化されていればサブクラス)が参照され、クラスメソッドを呼び出すことが出来るようになります。

62
61
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
62
61