最近我在Swift中試驗了賦值運算符,並遇到了一個問題,我找不到解決方案。我可以使用自定義賦值運算符初始化變量嗎?
考慮以下結構:
struct Box<T> {
let value: T
}
struct MyStruct {
let myProperty: String
init(boxedProperty: Box<String>) {
self.myProperty = boxedProperty.value
}
}
似乎很簡單,但想象MyStruct
接受20個盒裝的性質 - 他們每個人都需要通過訪問Box
實例的value
財產「開箱」。現在想象擁有MyStruct
的20個版本。
這將導致數百.value
線,這是相當多的。相反,爲了減少代碼混亂,我想使用一個自定義賦值運算符,它隱式地「解開」Box
並將其值賦給一個變量。
考慮這個簡單的例子(沒有可選性支持等):
infix operator <|= {
associativity right
precedence 90
assignment
}
func <|= <T>(inout lhs: T, rhs: Box<T>) {
lhs = rhs.value
}
理想情況下,我想用<|=
操作向右走,像這樣:
init(boxedProperty: Box<String>) {
self.myProperty <|= boxedProperty
}
但不幸的是(和相當可預測?),這是行不通的,因爲myProperty
變量在用於函數之前未初始化:
error: variable 'self.myProperty' passed by reference before being initialized
self.myProperty <|= boxedProperty
^
我可以確保編譯器我的assignment
運算符函數總是初始化變量(也稱爲a.k.a.其操作數爲lhs
)?另外,如果您有不同方法的想法,請隨時發表評論。
注:實際情況更爲複雜,需要的不僅僅是訪問value
propterty一個Box
結構的更「開箱」。
您的問題不適合使用框和屬性的數組? init(boxedProperties:[Box]){self.myProperties = boxedProperties.map {%0.value}}有了這個,20個或200個屬性,無論如何。 –
GoZoner
@GoZoner號現實生活中實際上是'init(anEnumValue:MyEnum)'。枚舉值包含不同的關聯值,它們需要雙「拆箱」。 – akashivskyy
與其他Swift'賦值'操作符不同(除了實際賦值爲'='),您不需要'inout'參數 - 因爲如您所知,您從未實際引用該值。但是,在表面上你正在交易:'self.myProperty <| = boxedProperty'爲'self.myProperty = boxedProperty.value'。我不明白在這種情況下運營商的優勢,但我願意承認我不能看到你的實際問題。 – GoZoner