斯威夫特“与"关键词 [英] Swift "with" keyword
问题描述
Swift 中with"关键字的用途是什么?到目前为止,我发现如果您需要覆盖现有的全局函数(例如 toDebugString),可以使用该关键字.
What's the purpose of "with" keyword in Swift? So far I have found that the keyword can be used if you need to override an existing global function, such as toDebugString.
// without "with" you get "Ambiguous use of 'toDebugString'" error
func toDebugString<T>(with x: T) -> String
{
return ""
}
toDebugString("t")
推荐答案
with
是不是关键字 - 它只是一个外部参数标识符.这也适用:
with
is not a keyword - it's just an external parameter identifier. This works as well:
func toDebugString<T>(whatever x: T) -> String
由于 toDebugString
函数已经定义,通过使用外部参数你正在创建一个重载:相同的函数名称,但不同参数.在这种情况下,参数是相同的,但使用外部名称标识,并且在 swift 中使其成为具有不同签名的方法,因此是重载.
Since the toDebugString<T>(x: T)
function is already defined, by using an external parameter you are creating an overload: same function name, but different parameters. In this case the parameter is the same, but identified with an external name, and in swift that makes it a method with a different signature, hence an overload.
为了证明这一点,请将其粘贴到 Playground 中:
To prove that, paste this in a playground:
func toDebugString<T>(# x: T) -> String {
return "overload"
}
toDebugString(x: "t") // Prints "overload"
toDebugString("t") // Prints "t"
第一个调用重载的实现,而第二个使用现有函数
The first calls your overloaded implementation, whereas the second uses the existing function
建议阅读:函数参数名称
这篇关于斯威夫特“与"关键词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!