Swift で class変数もどきを作る (Type Properties)

Swiftを軽く触り出しています。全体的に短く書けるし、機能強化もされていて
書きやすくなった印象はありますが、まだまだこれから変わっていくんだろうなということも感じています。

class変数

そんな今後に期待な機能のひとつとして class変数があります。 期待して書いてみるとエラーになりますが、「not yet supported」と今後やってくれそうな気配があります。

// Error
class let StartMonitoringNotification = "StartMonitoringNotification"

Type Properties

The Swift Programming Language: Properties
調べてみると type properties という機能があり struct、enum、class にpropetyを持たせることができます。

struct SomeStructure {
    static var storedTypeProperty = "Some value."
    static var computedTypeProperty: Int {
        // return an Int value here
    }
}
enum SomeEnumeration {
    static var storedTypeProperty = "Some value."
    static var computedTypeProperty: Int {
        // return an Int value here
    }
}
class SomeClass {
    class var computedTypeProperty: Int {
        // return an Int value here
    }
}

お、これ使ったらええやん

ということで type properties を使うと

class var StartMonitoringNotification: String { return "StartMonitoringNotification" }

こう書けます。

もう少しEnumっぽく書きたい

上記の例は notifcation のメッセージ名ですが、少し増えてきたので BeaconManager.Notification.StartMonitoring というような感じで書きたくなってきました。

最初考えた実装

公式Document読む前に考えた実装は、Structをinstance化して Type Propertiesとして定義するというやり方。

    struct _Notification {
        let ChangeBluetoothState = "ChangeBluetoothState"
        let AuthorizationState   = "AuthorizationState"
        let StartMonitoring      = "StartMonitoring"
    }
    class var Notification: _Notification { return _Notification() }

最終的な実装

    struct Notification {
        static let ChangeBluetoothState = "ChangeBluetoothState"
        static let AuthorizationState   = "AuthorizationState"
        static let StartMonitoring      = "StartMonitoring"
    }

struct(またはenum) のみでok!!