Swift “with” keyword

前端 未结 1 1961
耶瑟儿~
耶瑟儿~ 2020-12-10 07:53

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

相关标签:
1条回答
  • 2020-12-10 08:14

    with is not a keyword - it's just an external parameter identifier. This works as well:

    func toDebugString<T>(whatever x: T) -> String
    

    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.

    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

    Suggested reading: Function Parameter Names

    0 讨论(0)
提交回复
热议问题