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

Discussion in 'iOS Programming' started by chrono1081, Apr 21, 2016.

  1. chrono1081 macrumors 604

    chrono1081

    Joined:
    Jan 26, 2008
    Location:
    Isla Nublar
    #1
    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.
     
  2. AxoNeuron macrumors 65816

    AxoNeuron

    Joined:
    Apr 22, 2012
    Location:
    The Left Coast
    #2
    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.
     
  3. Mascots, Apr 22, 2016
    Last edited: Apr 22, 2016

    Mascots macrumors 65816

    Mascots

    Joined:
    Sep 5, 2009
    #3
    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")
    
     
  4. chrono1081 thread starter macrumors 604

    chrono1081

    Joined:
    Jan 26, 2008
    Location:
    Isla Nublar

Share This Page