Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS Swift Functions and Optionals Functions Creating a Function

Why can't I?

I know I ask many questions. It says: "You shouldn't call println directly. It needs to be in the body of the function." What does that mean?

greeting.swift
func greeting() {
println("Hello")
}
greeting()

2 Answers

rdaniels
rdaniels
27,258 Points

your printIn IS in the body of the function, it's embedded inside the curly braces...

Tommy Choe
Tommy Choe
38,156 Points

Hey Joshua,

the reason why you should place println() inside of the function is so that you could call the function whenever you need to. For the example you provided, it would actually be much more efficient if you actually called println() directly whenever if you simply wanted to print out "Hello" like so:

println("Hello")

In this case, it's far easier to directly call println() because you're only executing one line of code. So it would take longer if you made a function just so you can reuse that one statement. However, in real-life situations, you might want to reuse SEVERAL lines of code like this:

let firstName = "John"
let lastName = "Swift"
let fullName = firstName + lastName
println(fullName)

As you can see, you probably don't want to retype this over and over again, so you would want to place it all in a function so that you can reuse it by calling the function.

func getName(){
   let firstName = "John"
   let lastName = "Swift"
   let fullName = firstName + lastName
   println(fullName)
}

Call it by the function name

getName()

The instructor told you not to call println() directly (even though it's probably more efficient to do so) just for the sake of showing you a simple example of how to use a function.

Hope that helps!