假設我有兩個功能來創建手勢:
func makeGesture1() -> some Gesture {
...
}
func makeGesture2() -> some Gesture {
...
}
我想像這樣使用它們:
Text("abc")
.gesture( someCondition? makeGesture1() : makeGesture1().simultaneously(with: makeGesture2())
我得到了錯誤:
'? 中的結果值 :' 運算式具有不匹配的型別 'SimultaneousGesture<some Gesture, some Gesture>' 和 'some Gesture'
如果我用函式包裝運算式:
func makeGestureConditionally() -> some Gesture() {
if someCondition {
return makeGesture1()
} else {
return makeGesture1().simultaneously(with: makeGesture2())
}
}
我得到了錯誤:
函式宣告了一個不透明的回傳型別,但其主體中的回傳陳述句沒有匹配的底層型別
我發現我可以執行以下操作,但我想知道是否有一種不那么hacky的方法,一種適當的方法:
someCondition
? AnyGesture(makeGesture1().simultaneously(with: makeGesture2()).map { _ in () })
: AnyGesture(makeGesture1().map { _ in () })
uj5u.com熱心網友回復:
當您使用“不透明回傳型別”(如some Gesture)時,您向編譯器斷言您將只回傳 1 個特定的具體Gesture型別,您只是不想寫出其完整簽名。這就是您不能在運行時動態回傳不同型別的原因。這就是三元運算子 ( ?:) 也失敗的原因;三元運算子只接受相同型別的運算元。
一種解決方法是使用 SwiftUIViewBuilder讓 SwiftUI 運行時根據條件在視圖上激活正確的手勢。
var baseView: some View {
Text("123")
}
@ViewBuilder
var content: some View {
if someCondition {
baseView
.gesture(makeGesture1())
} else {
baseView
.gesture(makeGesture1().simultaneously(with: makeGesture2()))
}
}
這是允許的,因為 SwiftUI 在內部使用一種叫做“結果構建器”的東西if在運行時只回傳陳述句的1 個分支,陳述句的每個分支if都有一個具體的型別。
在SwiftUI,避免使用任何型別擦除包裝紙(AnyView,AnyGesture等),因為它們增加了SwiftUI計算開銷。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/348898.html
