Skip to Content
iOS 15 Programming Fundamentals with Swift
book

iOS 15 Programming Fundamentals with Swift

by Matt Neuburg
October 2021
Intermediate to advanced content levelIntermediate to advanced
786 pages
21h 17m
English
O'Reilly Media, Inc.
Book available
Content preview from iOS 15 Programming Fundamentals with Swift

Chapter 2. Functions

Nothing is so characteristic of Swift syntax as the way you declare and call functions. Probably nothing is so important, either! As I said in Chapter 1, all your executable code is going to be in functions; they are where the action is.

Function Parameters and Return Value

Remember those imaginary machines for processing miscellaneous stuff that you drew in your math textbook in elementary school? You know the ones I mean: with a funnel-like “hopper” at the top, and then a bunch of gears and cranks, and then a tube at the bottom where something is produced. A function works like that: you feed some stuff in, the stuff is processed in accordance with what this particular machine does, and something is produced. The stuff that goes in is the input; what comes out is the output. More technically, a function that expects input has parameters; a function that produces output has a result.

Here’s the declaration for a silly but valid function that expects two Int values, adds them together, and produces that sum:

func sum (_ x:Int, _ y:Int) -> Int {
    let result = x + y
    return result
}

The syntax here is very strict and well-defined, and you can’t use Swift unless you understand it perfectly. Let’s pause to appreciate it in full detail. I’ll break the first line into pieces so that I can call them out individually:

func sum                      1
    (_ x:Int, _ y:Int)        
    -> Int {                   let result ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

iOS 15 Programming for Beginners - Sixth Edition

iOS 15 Programming for Beginners - Sixth Edition

Ahmad Sahar, Craig Clayton
Programming iOS 14

Programming iOS 14

Matt Neuburg

Publisher Resources

ISBN: 9781098118495Supplemental ContentErrata Page