【问题标题】:"Unable to infer type of a closure parameter 'b' in the current context". Getting this error while calling the function“无法在当前上下文中推断闭包参数 'b' 的类型”。调用函数时出现此错误
【发布时间】:2021-12-31 22:51:39
【问题描述】:

调用函数时出错。

func hitService<T : Codable>(urlS: String , completion : @escaping (T) -> Void) {
    
    guard let url = URL(string: urlS) else {return}
    
    
    let session = URLSession.shared
    
    let _ = session.dataTask(with: url) { dt, resp, err in
        
        
        let decoder = JSONDecoder()
        
        if let d = dt {
            
            do {
                let obj = try decoder.decode(T.self, from: d)
                completion(obj)
            } catch {print(error.localizedDescription)}
        }
    }.resume()
}

像这样调用函数并得到错误。 我也尝试在 中传递数据类型。

 hitService(urlS: urlStr) { b in
        
        
        
  }

【问题讨论】:

  • 请更新您的问题以显示您如何调用该函数
  • hitService(urlS: urlStr) { b in }

标签: ios swift xcode generics swift3


【解决方案1】:

泛型函数依赖于您在调用它时指定类型,以便推断它使用的类型。

在这种情况下,您需要提供闭包参数 b 的类型,即

hitService(urlS: urlStr) { (b: MyType) in
    
}

【讨论】:

  • 谢谢哥们。我还注意到,如果我在调用 print(b as String) 之类的函数时在里面写了一些东西,那么错误就会消失。
猜你喜欢
  • 1970-01-01
  • 2019-04-05
  • 2018-11-08
  • 1970-01-01
  • 2019-05-14
  • 2017-02-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多