Can someone please explain this Swift syntax to me (NSURL(string...) )

chrono1081

macrumors 604
Original poster
Jan 26, 2008
7,434
1,402
Isla Nublar
Hi guys,

I'm hung up on some Swift syntax that I'm not sure why it is the way it is:

Code:
if let url = NSURL(string: "http://www.google.com")!
I get that it has a ! because the init method returns an optional, but what is the "string: " for? Is it just an explicit parameter name? I was under the impression the first parameter in Swift was not named, only subsequent parameters.
 

AxoNeuron

macrumors 65816
Apr 22, 2012
1,241
844
The Left Coast
I believe that if there are two versions of the same function that accept different (single) parameters, it requires you to explicitly type it. So since there's two different NSURL initialization methods that both accept a single patameter:

Code:
NSURL(string: );
NSURL(path: );
The compiler needs to know which one you're using, so the parameter name must be explicit. This is just a guess though so I could be wrong.
 
  • Like
Reactions: chrono1081

Mascots

macrumors 68000
Sep 5, 2009
1,589
1,246
What AN said and you can also force functions to explicitly require the first parameter definition with Swift by specifying an external parameter name. It's useful for situations that you need to clearly define what value is incoming (among other things):
Code:
convenience init?(string URLString: String)
This is the signature for NSURL's convenience initializer, notice the string URLString.

You can do the opposite, too, to omit parameter names:
Code:
do(variable: String, _ internalName: String)
[...]
do("the", "shimmy")
 
Last edited: