Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

chrono1081

macrumors G3
Original poster
Jan 26, 2008
8,775
5,430
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.
 
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
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:
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.