What is the meaning of the ‘#’ mark in swift language

Update (Swift 3.*…)

the default behavior of the first parameter’s signature was changed drastically. To understand how argument labels (ex. “external parameters”) and parameter names (ex. “local parameters”) work, please read the chapter “Function Argument Labels and Parameter Names” from the Apple’s Swift-book.

Some examples:

func someFunction(parameterName: Int) { parameterName }
someFunction(parameterName: 5) // argument label not specified

func someFunction(argumentLabel parameterName: Int) { parameterName }
someFunction(argumentLabel: 5) // argument label specified

func someFunction(_ parameterName: Int) { parameterName }
someFunction(5) // argument label omitted

There is no difference in this behavior between methods and functions.


Update (Swift 2.*)

The feature described below was deprecated, one need to write the parameter name twice to get the same behavior as with hash symbol before.


Update (examples)

For functions: when the function is called and purpose of some parameters is unclear, you provide external names for those parameters.

func someFunction(parameterName: Int) { parameterName }
someFunction(5) // What is the meaning of "5"? 

func someFunction(externalParameterName parameterName: Int) { parameterName }
someFunction(externalParameterName: 5) // Now it's clear.

But if external and local names are the same, you just write a hash symbol before the parameter name.

func someFunction(#parameterName: Int) { parameterName }
// It's actually like:
// func someFunction(parameterName parameterName: Int) { parameterName }
someFunction(parameterName: 5)

For methods: by default first parameter name is only local (like by functions), but second and subsequent parameter names are both local and external (like as you write a hash symbol before the parameter name, this # is implicitly there):

class SomeClass {
    func someMethodWith(firstParameter: Int, andSecondParameter: Int) { ... }
}
SomeClass().someMethodWith(5, andSecondParameter: 10)

You can use # (or add an explicit external name) for the first parameter of the method too, but it’ll not match Objective-C-style calling.

class SomeClass {
    func someMethodWith(#firstParameter: Int, andSecondParameter: Int) { ... }
}
SomeClass().someMethodWith(firstParameter: 5, andSecondParameter: 10)

Original answer

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.

Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks. https://itunes.apple.com/ru/book/swift-programming-language/id881256329?l=en&mt=11

Leave a Comment