gpt4 book ai didi

swift - 分配后无法推断通用参数 'T'

转载 作者:行者123 更新时间:2023-12-04 01:15:37 24 4
gpt4 key购买 nike

// Xcode 11.6 / Swift 5

import Foundation

func f<T>(_: (T) -> Void) { }

@discardableResult
func g(_: Int) -> Int { 0 }

f { g($0) } // compiles fine

f { let _ = g($0) } // Generic parameter 'T' could not be inferred

在上面的代码中,泛型函数 f 需要一个函数作为它的参数,该函数接受类型为 T 的参数。

g 函数接受一个 Int 类型的参数。

当我编写 f { g($0) } 时,代码会编译。我相信(如果我错了请纠正我)这个编译是因为编译器可以推断 T 是一个基于 Int g 的参数类型。

但是,当我尝试对 g 的返回值做一些事情时,例如在 let _ = g($0) 行中,编译器提示它无法再推断出 T 的类型。

在我看来,g 的返回类型应该与编译器如何推断 T 的类型无关,但显然它确实如此。

任何人都可以阐明为什么会发生这种情况,以及可以采取什么措施(如果有的话)来纠正它?

最佳答案

这可能是也可能不是编译器错误。

众所周知,Swift 不会尝试推断某些闭包的类型,即多语句闭包,as said in SR-1570 :

This is correct behavior: Swift does not infer parameter or return types from the bodies of multi-statement closures.

但是,您的闭包仅包含一个语句,具体来说是一个声明。有可能,尽管很奇怪,他们将其设计为如果闭包也包含一个声明,则 Swift 不会尝试推断类型。例如,这也不编译

f { let x: Int = $0 } // nothing to do with "g"! The issue seems to be with declarations

如果这是设计使然,其背后的基本原理可能是因为闭包中的单个声明无论如何都没有多大意义。无论声明什么,都不会被使用。

但同样,这只是推测,也可能是一个错误。

要修复它,只需将其设为非声明即可:

f { _ = g($0) } // this, without the "let", is IMO the idiomatic way to ignore the function result

或者

f { g($0) } // g has @discardableResult anyway, so you don't even need the wildcard

关于swift - 分配后无法推断通用参数 'T',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63461738/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com