我希望能夠擁有靜態屬性(字段)的類,這些靜態屬性是從基類繼承的或從協議繼承的混合的。每個班級都應該有自己的財產執行。可能嗎?優選地,它是不可變的。從基類或協議繼承的靜態字段 - 如何?
class C1 {
static let stProperty = "my prorepty1"
}
class C2 {
static let stProperty = "my prorepty2"
}
我希望能夠擁有靜態屬性(字段)的類,這些靜態屬性是從基類繼承的或從協議繼承的混合的。每個班級都應該有自己的財產執行。可能嗎?優選地,它是不可變的。從基類或協議繼承的靜態字段 - 如何?
class C1 {
static let stProperty = "my prorepty1"
}
class C2 {
static let stProperty = "my prorepty2"
}
當然,你可以做到這一點與協議:
protocol SomeProtocol {
static var foo: String { get }
}
class One: SomeProtocol {
class var foo: String {
get {
return "This is One"
}
}
}
順便說一句我與Rob納皮爾低於同意這是有點過了一個古怪的功能。我認爲這可能是用例,但我也認爲這些可以更好地與其他語言功能實現
也許是更好的SomeProtocol轉換爲一類? – 2015-03-13 14:30:05
這將取決於你想解決什麼問題。在許多情況下,繼承是錯誤的解決方案。問題是,所有的東西是否基本上都是「一種X」(在這種情況下,繼承是好的),或者他們只是「做類X事情」(在這種情況下協議是正確的答案)。如有疑問,請使用協議。 – 2015-03-13 15:01:11
這是可能的,但它很難在Swift中使用它。你打算如何參考這個屬性?讓我們從一個超簡單的實現開始吧:
protocol SomeProtocol {
static var prop: String { get }
}
class C1: SomeProtocol {
static let prop = "This is One"
}
好。所以現在我想要一個使用此功能:
func useProp(x: SomeProtocol) -> String {
return x.prop
// 'SomeProtocol' does not have a member named 'prop'
}
這是行不通的。 x
是一個實例,但我想要的類型。
// Accessing members of protocol type value 'SomeProtocol.Type' is unimplemented
func useProp(x: SomeProtocol.Type) -> String {
return x.prop
}
這大概是它會工作的某一天給出的單詞「未實現的。」但今天不行。
func useProp(x: SomeProtocol) -> String {
// Accessing members of protocol type value 'SomeProtocol.Type' is unimplemented
return x.dynamicType.prop
}
同樣的事情。
今天,你真的要在對象上本身掛起來,而不是使用static
或class
:
protocol SomeProtocol {
var prop: String { get }
}
class C1: SomeProtocol {
let prop = "This is One"
}
func useProp(x: SomeProtocol) -> String {
return x.prop
}
這不是在很多情況下那麼可怕,因爲該類的值可能也的任何給定的類的實例的值。這是我們今天所能做的。
當然你的問題可能是你還沒有實例,你需要這些信息來構建一個實例。今天真的很難,你應該重新考慮你的設計。你通常必須使用一些其他模式,比如Builder。有關更多信息,請參閱Generic Types Collection。
現在你也說:
or "mixed" from a protocol
我不會說 「混」 在這裏。如果你真的認爲這就像一個Ruby「mixin」,那麼今天Swift就沒有這種東西。 Swift人經常將這個特性稱爲「默認實現」,目前還不可能(儘管我確實期望它最終會出現)。你可以在協議中做的唯一事情就是說實現者必須以某種方式提供這種方法。你不能爲他們提供。
羅布我看到你編輯我的答案,並將'class'改爲'static',但這在Xcode 6.2/Swift 1.1中不適用於我。這是Swift 1.2的變化嗎? – 2015-03-13 14:02:10
它可能是;我正在測試測試版,他們確實對類/靜態進行了一些更改。對困惑感到抱歉。 – 2015-03-13 14:08:23
'C1.prop' ........ – 2015-03-13 14:27:12
protocol P {
class var stProperty: String { get }
}
class C1 {
class var stProperty: String {
return = "my property1"
}
}
class C2 {
class var stProperty: String {
return = "my property2"
}
}
用法:
C2.prop //"my property2"
如果你嘗試:
C2.prop = "new value" //"cannot assign to the result of this expression"
如何讓它「讓」而不是「var」? – 2015-03-14 08:14:43
什麼是你的具體使用情況本 – 2015-03-13 15:00:07