How to declare Default Values for the function parameter in swift?

0 votes
302 views
asked Mar 4, 2015 in Swift by kalpana (3,995 points)
Hi

  How to declare Default Values for the function parameter in swift?

1 Answer

0 votes
answered Mar 4, 2015 by codeg (2,600 points)

Default Parameter Values

You can define a default value for any parameter as part of a function’s definition. If a default value is defined, you can omit that parameter when calling the function.

NOTE

Place parameters with default values at the end of a function’s parameter list. This ensures that all calls to the function use the same order for their non-default arguments, and makes it clear that the same function is being called in each case.

Here’s a version of the join function from earlier, which provides a default value for its joiner parameter:

func join(string s1: String, toString s2: String,

withJoiner joiner: String = " ") -> String {

return s1 + joiner + s2

}

If a string value for joiner is provided when the join function is called, that string value is used to join the two strings together, as before:

join(string: "hello", toString: "world", withJoiner: "-")

// returns "hello-world"

...