Swift basics - functions

Defining a function with parameters and return types:
func hello(name: String) -> Void{}
//the above does not have a return value

func hello(name: String) -> String
{ let ret = "Hello " + name
return ret}

To call the above function:
let msg = hello(name: "Mary")

//I am aware of the return value but don't want to use it:
_ = hello(name: "Mary")
You can also do this:
@discardableResult func hello(name: String) -> String
{
let ret = "Hello " + name
return ret
}

Multi-parameter functions:
func hello(name: String, greeting: String)
{ }
To call:
hello(name:"Mary", greeting:"Whats up")

You can define a parameter with default values.
func hello(name: String, greeting: String = "Whats up"){}
When calling, you can either call with the greeting or without it:
hello(name: "Mary")
hello(name:"Mary", greeting:"Good day")
We can also declare multiple default values:
func hello(name: String = "Mary", greeting: String="Whats up"){}

You can return an array:
func getNames() -> [String]

You can return a tuple:
func getFood() -> (dish: String, flavour: String, calories: Double)
{
 let ret = ("Ice cream", "Strawberry", 150.0)
return ret
}

Returning optional values:
You cannot do this:
func getName() -> String{return nil}
You can do this:
func getName() -> String?
{return nil}
A tuple can also be optional:
func getFood(id: Int) -> (dish: String, flavour: String, calories: Double)?
{
 if id == 1
{ return ("Ice cream", "Strawberry", 150.0)}
return nil}

We can also return a tuple that has an optional value:
func getFood(id: Int) -> (dish: String, flavour: String, calories: Double?)
{
 return ("Ice cream", "Strawberry",  nil)
}

External parameter names:
The parameter names that the calling function uses and the one used internally inside the function are different.
For example:
func setFood(dish a: String, flavour b: String, calories c: Double)
{
 print(a+b+c)
}

Variadic parameters:
Accepts zero or more values of a specified type
func hello(greeting: String, names: String...)
{
 for each name in names{}}
We can call it like this:
hello("Whats up", "Mary", "John")

inout parameters:
When the changes made to the parameter inside the function persists outside of the function.
Cannot be used with variadic parameters or those with default values:

func changeName(name: inout String, second: inout String)
{
  name = second
  second = "haha"
}

When calling the function:
var  x = "A"
var y = "B"
changeName(name: &x, second: &y)
//The changes will be made to variables x and y.

Comments

Popular posts from this blog

Setting up a playground

Go to another page