What is Shorthand External Parameter Names in swift?

0 votes
65 views
asked Mar 4, 2015 in Swift by kalpana (3,995 points)
Hi All

  What is Shorthand External Parameter Names in swift?

1 Answer

0 votes
answered Mar 4, 2015 by codeg (2,600 points)

If you want to provide an external parameter name for a function parameter, and the local parameter name is already an appropriate name to use, you do not need to write the same name twice for that parameter. Instead, write the name once, and prefix the name with a hash symbol (#). This tells Swift to use that name as both the local parameter name and the external parameter name.

This example defines a function called containsCharacter, which defines external parameter names for both of its parameters by placing a hash symbol before their local parameter names:

func containsCharacter(#string: String, #characterToFind: Character) -> Bool {

for character in string {

if character == characterToFind {

return true

}

}

return false

}

This function’s choice of parameter names makes for a clear, readable function body, while also enabling the function to be called without ambiguity:

let containsAVee = containsCharacter(string: "aardvark", characterToFind: "v")

// containsAVee equals true, because "aardvark" contains a "v"

 

...