parm530
4/22/2020 - 5:22 PM

Lesson 5: Functions

Functions

  • Declaring a function:
    func name() { // stuff }
    
  • Call function: name()

Functions with Parameters

func myFunction(parameter: DataType) {} 

// A function declaration
func getMilk(bottles: Int) { 
  var cost = bottles * 1.5
}

// Calling the function
getMilk(bottles: 2)
  • Even though we don't always add the datatype upon creating swift variables, they do get assigned one upon creation - type inference
  • With specifying a type: var parm: Int = 365474

Scope

  • Describes when a function can be accessed or used

Parameter Names

func checkAnswer(userAnswer: String) {
  // userAnswer is the internal parameter name
  // the name we can use in here

}

// USING EXTERNAL PARAMETER NAMES
func checkAnswer(answer userAnswer: String) {
  // answer is the EXTERNAL parameter name
  // the name we can use NOT IN HERE BUT WHEN WE CALL OUR FUNCTION
  // useerAnswer is still valid to use in here

}

// USING _ to replace the external parameter name
func checkAnswer(_ userAnswer: String) {
  
}

// to call this function:
var userAnswer = ... /// if you had a variable named userAnswer
checkAnswer(userAnswer: userAnswer)

// Calling the function with external parameter name
checkAnswer(answer: userAnswer)

// Using the _ for the external parameter name
checkAnswer(userAnswer) // no need to specify the parameter name

Functions with RETURN types

func nameOfFunc (arg: TypeofArg) -> returnType {
  // code
  return something // something must match the returnType
}

// Example
func getMilk(money: Int) -> Int {
  let change = money -2
  return changs
}

// You can then capture the output in a variable
va val = getMilk(money: 4) // value = 2