ios - parameters' label in a function -


i learning swift, in apple's tutorial, has following code snippet when introducing function:

func greet(name: string, lunch: string) -> string {     return "hello \(name), eat \(lunch)." } //why here 'lunch' cannot removed?  greet("bob", lunch: "tuesday") 

the code defined greet(string, string) function, when calls function:

greet("bob", lunch: "tuesday") 

the 1st parameter doesn't have label 'name', 2nd 1 has label 'lunch', if remove label 'lunch', compiler error says "missing argument label lunch in call"

why 1st parameter without label, not 2nd one?

clarity

the main reason clarity.

in swift's function naming style, method name implies first argument, not later arguments.

for example:

nsnotificationcenter.defaultcenter().addobserver(self, selector: "dosomething", name: uiscreenbrightnessdidchangenotification, object: nil) 

self implied syntax observer you're adding notification center.

greet("bob", "tuesday") imply bob being greeted, doesn't tell tuesday has things. makes code less readable, isn't allowed.

default parameter values

a second reason default parameter values. consider instead function:

func greetforlunch(name: string, food: string = "pasta", restaurant: string = "olive garden") -> string {     return "hello \(name). eat \(food) @ \(restaurant)?" } 

since 2 latter arguments have default values, can omit 1 or both of them, example:

greetforlunch("bob", food: "endless breadsticks") // "hello bob. eat endless breadsticks @ olive garden?" 

but if didn't specify food here, so:

greetforlunch("bob", "endless breadsticks") 

it ambiguous whether second argument should assigned food or restaurant.


Comments

Popular posts from this blog

Android : Making Listview full screen -

javascript - Parse JSON from the body of the POST -

javascript - Chrome Extension: Interacting with iframe embedded within popup -