Functions

I’m sharing the September post a day early.

There’s nothing really profound in this one - I’m just continuing to search for visual ways to describe functions.

This one will be included in the free update (well free if you own it already - if not you can buy it now and get the free update once it ships) of A Swift Kickstart.

This book is for folks new to Swift and so I gently start with the classic Hello World function. I’ve implemented it as “Hi World” because it fits better in comic form.

I know that this daring decision might throw you but it really isn’t to challenge years of tradition so much as to fit in large font in small rectangles.

func hi() {
    print("Hi, World!")
 }

Although this is a good and quick example in Xcode playgrounds, Swift playgrounds does not have a console which drives us to quickly include a function that returns a String rather than print it to the console.

func hi() -> String {
	"Hi, World!"
}

By the way, if you haven’t been keeping up with Swift, this might look funny as we don’t need to include the return in a function with only a single expression. In other words we don’t need the following

func hi() -> String {
	// the return in the following line is superfluous
	return "Hi, World!"
}

“But Daniel,” you say, “it looks funny without the return.”

At first it does. Just as it looked funny, for those of us coming from Objective-C to see the return type at the end of the function signature or to not have semicolons at the end of a line.

It will grow on you.

In fact, you’ll wonder why return isn’t just assumed for the last expression of a function that is supposed to return something no matter how many lines it is.

i.e. it feels silly that this is fine:

func hi() -> String {
	"Hi, World!"
}

but this doesn’t compile

func hi() -> String {
	print("This doesn't compile - the next line needs a return")
	"Hi, World!"
}

Anyway, back to the point. We really want functions that take input and produce output. That is the final form of this silly example.

func hi(name: String) -> String {
	"Hi, \(name)!"
}

Here it is in comic form.

Functions

As always, let me know what you think.