代码之家  ›  专栏  ›  技术社区  ›  swiftPunk Alexander

如何解决无法推断闭包参数类型的问题?

  •  1
  • swiftPunk Alexander  · 技术社区  · 4 年前

    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!
    
                    })
                    
                }
            
        }
        
    }
    
    1 回复  |  直到 4 年前
        1
  •  1
  •   Asperi    4 年前

    泛型参数( T 在你的情况下)是 input ,所以您应该在函数输入时给出所有类型化的参数(编译器不会跳转到内部循环实现以查找类型的位置)

    因此,解决方案是在闭包中提供显式类型,如

    testValue(value: { (newValue: Bool) in      // << here !!
    
        bool = newValue      // <<: This or That!
    
        print(newValue)    // <<: This or That!
    
    })
    

    更新: 你可以留下 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)")
                    })
                }
        }
    }
    

    enter image description here