2014-09-12 50 views
0

由於對象存儲屬性不支持Type屬性,因此具有struct type屬性似乎對我來說是合理的解決方法。問題:我應該使用內部結構嗎?存儲屬性的Swift Type屬性

我喜歡內部結構語法,因爲它好像封裝了接口,但我不確定它是否浪費了每個實例的寶貴內存空間?會嗎?

例如

class MyClass { 
    // inside the class 
    struct MyStatic { 
    static let MyConstant = "abc" 
    } 
} 

// in the same file 
struct MyStatic { 
    static let MyConstant = "abc" 
} 

class MyClass { 

} 
+0

你的意思是「自** **靜態類型屬性不支持......」? – 2014-09-12 17:25:56

+0

我的意思是存儲屬性的類類型屬性。目前對於類類型屬性,此時僅支持類計算屬性。 – Sean 2014-09-12 17:32:21

+0

你能發表一個你真正想要完成的事情嗎?我不確定你在你的例子中想要做什麼。它看起來像一個名爲MyConstant的String類型的變量存儲在名爲MyStatic的結構中,位於名爲「MyClass」的類的內部或外部。 – Ideasthete 2014-09-12 18:12:52

回答

0

如果你想在最接近於Type Property,那麼你要使用一個內部struct;它不會被存儲在類的每個實例中。如果您在class之外定義struct,那麼它將變成全球性的,這不是同一回事。

structclass定義:內class定義

struct MyStatic { 
    static let MyConstant = "abc" 
} 

class MyClass1 { 
    func test() { println(MyStatic.MyConstant) } // Works because MyStatic is Global 
} 

class MyClass2 { 
    func test() { println(MyStatic.MyConstant) } // Works because MyStatic is Global 
} 

struct

class MyClass1 { 
    struct MyStatic { 
     static let MyConstant = "abc" 
    } 
    func test() { println(MyStatic.MyConstant) } 
} 

class MyClass2 { 
    func test() { println(MyStatic.MyConstant) } // Compile error: MyStatic is not accessible 
} 

這也可以讓你重新定義每classMyConstant(這是什麼類型屬性是到與經):

class MyClass1 { 
    struct MyStatic { 
     static let MyConstant = "abc" 
    } 
    func test() { println(MyStatic.MyConstant) } // abc 
} 

class MyClass2 { 
    struct MyStatic { 
     static let MyConstant = "def" 
    } 
    func test() { println(MyStatic.MyConstant) } // def 
} 

您甚至可以添加一個計算的類型屬性來模擬存儲一個:

class MyClass1 { 
    struct MyStatic { 
     static let MyConstant = "abc" 
    } 

    class var MyConstant: String { 
     get { return MyStatic.MyConstant } 
    } 

    func test() { println(MyClass1.MyConstant) } 
}