O'Reilly logo

Swift Essentials - Second Edition by Dr. Alex Blewitt

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Functions

Functions can be created using the func keyword, which takes a set of arguments and a body of statements. The return statement can be used to leave a function:

> var shopping = [ "Milk", "Eggs", "Coffee", "Tea", ]
> var costs = [ "Milk":1, "Eggs":2, "Coffee":3, "Tea":4, ]
> func costOf(items:[String], _ costs:[String:Int]) -> Int {
.   var cost = 0
.   for item in items {
.     if let ci = costs[item] {
.       cost += ci
.     }
.   }
.   return cost
. }
> costOf(shopping,costs)
$R0: Int = 10

The return type of the function is specified after the arguments with an arrow (->). If missing, the function cannot return a value; if present, the function must return a value of that type.

Note

The underscore (_) on the front of the costs parameter is required to avoid ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required