我有一個函式回傳一個型別為 T 的閉包,在發送它之前,將在函式內部選擇?? T 的型別!我只是讓我的示例代碼非常簡單來顯示問題。問題是我不能輸入或因為錯誤而有超過一行的代碼,Unable to infer type of a closure parameter但我需要在那里運行超過一行的代碼!
func testValue<T>(value: @escaping (T) -> Void) {
let randomValue: Bool = true
value(randomValue as! T)
}
用例:
struct ContentView: View {
@State private var bool: Bool = Bool()
var body: some View {
Text("Hello, World!")
.onAppear() {
testValue(value: { newValue in
bool = newValue // <<: This or That!
//print(newValue) // <<: This or That!
})
}
}
}
uj5u.com熱心網友回復:
泛型引數(T在您的情況下)是input,因此您應該在輸入函式時提供所有型別的引數(編譯器不會跳轉到內部回圈執行以找到型別可能的位置)
所以解決方案是在閉包中提供顯式型別,比如
testValue(value: { (newValue: Bool) in // << here !!
bool = newValue // <<: This or That!
print(newValue) // <<: This or That!
})
使用 Xcode 13.1 / iOS 15 測驗
更新:您可以保留T函式并將其用作處理的輸入引數,例如
func testValue<T>(value: @escaping (T) -> Void) {
if T.self == Bool.self {
let randomValue: Bool = true
value(randomValue as! T)
} else if T.self == String.self {
let randomValue: String = "Test"
value(randomValue as! T)
}
}
struct ContentView: View {
@State private var bool: Bool = Bool()
var body: some View {
Text("Hello, World!")
.onAppear() {
testValue(value: { (newValue: Bool) in
bool = newValue
print(newValue)
})
testValue(value: { (newValue: String) in
print("Got: \(newValue)")
})
}
}
}

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/368979.html
