(你應該看看是否符合CustomStringConvertible
,但對於技術討論,在這裏如下...)
您可以,但是實施enum
包裝,每個包裝的情況下不同類型的關聯值(很像Optional<Int>
包裝.none
或.some(Int)
)。
enum WindDirection {
case asDegree(Float)
case asString(String)
}
有了這個,你可以讓你的實例變量windDirection
是兩個不同的包裝類型,這樣可以讓你期望的setter一個包裹類型,並在吸氣返回另一個包裝類型的包裝。例如:
class Foo {
private var _windDirection: WindDirection
var windDirection: WindDirection {
get {
switch _windDirection {
case .asDegree(let angle):
switch(angle) {
case 348.75..<360.0, 0..<11.25: return .asString("N")
case 11.25..<33.75: return .asString("NE")
/* ... */
case _ : return .asString("Not expected")
}
case _ : return .asString("Not expected")
}
}
set (newValue) {
if case .asDegree(_) = newValue {
_windDirection = newValue
}
}
}
init?(_ windDirection: WindDirection) {
guard case .asDegree(_) = windDirection else { return nil }
_windDirection = windDirection
}
}
用法示例(您需要處理的包裹關聯值的解纏在呼叫你的實例屬性,不過)
// attempt initialization
if let foo = Foo(.asDegree(11.0)) {
// getter
if case .asString(let windDirection) = foo.windDirection {
print(windDirection) // N
}
// setter
foo.windDirection = .asDegree(15.75)
// getter
if case .asString(let windDirection) = foo.windDirection {
print(windDirection) // NE
}
}
我很願意看到的答案,太多,但老實說,我希望答案是響亮的「不」 :-) – dasblinkenlight
答案** **是沒有,你真的需要一個'ValueTransformer' – vadian