Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift "with" keyword

Tags:

swift

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")
like image 378
Boon Avatar asked Aug 30 '14 14:08

Boon


1 Answers

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

like image 159
Antonio Avatar answered Oct 29 '22 01:10

Antonio