Reputation: 281
In Apple's book on Swift, I found this excerpt:
Methods on classes have one important difference from functions. Parameter names in functions are used only within the function, but parameters names in methods are also used when you call the method (except for the first parameter). By default, a method has the same name for its parameters when you call it and within the method itself. You can specify a second name, which is used inside the method.
I have absolutely no idea what this means. The example they give didn't clarify anything. Could someone please give me an example please? (Maybe explicitly show the difference the excerpt mentions.)
Upvotes: 1
Views: 77
Reputation: 13511
In Swift, you can define a function whose parameters have one name when called externally, but another name when you are using them as variables inside the function definition. This makes your code more readable, like an English sentence instead of code.
For example, you can define a file-writing function as below:
func writeData(data: NSData,
toFileName fileName: String,
withCompletionHandler completionHandler: () -> ()) {
// ...
}
From the outside, you will call the function using the parameter names toFileName
and withCompletionHandler
.
self.writeData(data, toFileName: "FileName.txt", withCompletionHandler: nil)
However, inside the function itself where you define the file writing behavior, you will need to access the arguments whose variable names are data
, fileName
, and completionHandler
.
func writeData( ... ) {
let successful = SomeFileWriter.writeData(data, fileName: fileName)
if successful == true {
completionHandler()
}
}
If you want the external and internal parameter names to be the same, you may explicitly use a hash mark in front of the parameter name:
func writeData(#data: NSData, #fileName: String, #completionHandler: () -> ()) {
}
But you don't need to do this. If you don't provide an external parameter name, Swift assumes that the internal and external parameter names are the same.
Upvotes: 2