Swiftのクラスメソッドの中でクラス定数を使う
私もちゃんと理解してないんだけど、メモ用。Swift限定の仕様じゃないかもしれない。
変なとこあったらご指摘ください。
Swiftのクラスメソッド(SwiftではType Methodかな)の中でクラス定数を使おうとした。
#define TEST_VALUE 1 @implementation TestClass
みたいになってるクラスを書き換えたかったのでやってみると、コンパイルエラーで止められる。。。
class ClassHasInstanceMethod { let testValue:Int = 1 class let testValue2:Int = 1 // Error! Class variables not yet supported func getValue() -> Int{ return testValue } class func getValue2() -> Int{ return testValue // Error! 'ClassHasInstanceMethod.Type' does not have a member named 'testValue' } } var instance = ClassHasInstanceMethod() println(instance.getValue()) // 1
not yet supportedってなんなんだって話なのですが、とりあえず使えない。
あとちゃんと定義してるのにdoes not have a member
って言われてさらに腑に落ちない。
(ちなみにjavaっぽくstaticもつけてみたけど、static letはだめっぽい)
結局いろいろ試行錯誤したら、下のようにするとどうにか動いた。
private let testValue:Int = 1 // Define constant out of class class ClassHasTypeMethod { class func getValue() -> Int{ return testValue } } println(ClassHasTypeMethod.getValue()) // 1
class宣言の外で定数を定義すると、そのファイル内で使える定数になるみたい
(他のクラスから使わないようにするならprivateをつける。)
そういわれてみればObj-Cの#defineも@implementationの前でやってるし、これが普通なのか・・・?