Home > OS >  How can I solve Unable to infer type of a closure parameter issue?
How can I solve Unable to infer type of a closure parameter issue?

Time:11-28

I have a function that returns a closure with type of T, the type of T will be chosen inside the function before sending it! I just made my example code heavily simple to show the issue. The issue is there that I can not type or have more than one line of code because of the error of Unable to infer type of a closure parameter but I need to run more than one line of code there!

func testValue<T>(value: @escaping (T) -> Void) {
    
    let randomValue: Bool = true
    value(randomValue as! T)
    
}

use case:

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!

                })
                
            }
        
    }
    
}

CodePudding user response:

Generics parameter (T in your case) is input, so you should give on input of function all arguments typed (compiler does not jump inside to cycle through implementation to find where the type could be)

So the solution is to provide explicit type in closure, like

testValue(value: { (newValue: Bool) in      // << here !!

    bool = newValue      // <<: This or That!

    print(newValue)    // <<: This or That!

})

Tested with Xcode 13.1 / iOS 15

Update: You can keep T in function and use it inside as input argument for processing, like

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)")
                })
            }
    }
}

enter image description here

  • Related