Reputation: 13
I am new to programming, particularly to the Swift language. I'm trying to print a string that contains a print function (I use string interpolation).
I don't understand why I got a strange output from this piece of code:
func newFunc() {
print("I print a message")
}
print("Function said: \(newFunc())")
I got the following output:
I print a message
Function said: ()
The message that was called by the function was executed before the "Function said: " words. I know I can use the return inside the function to get the correct output or use a variable to store this string, but I want to understand why I got the result described above.
Thanks in advance!
Upvotes: 0
Views: 221
Reputation: 63227
You're treating newFunc()
as if it returns a useful result (something that you can interpolate into "Function said: \(here)"
. But it doesn't return anything, which in Swift, is equivalent to returning Void
.
Void
is a type that models a return of nothing. It's equivalent to the empty tuple, ()
. If a function doesn't declare an explicit return type (such as newFunc()
), then it behaves as-if it declared a return type of Void
. Any time execution of a void-returning function reaches the end of its body, it's as if there's an implicit return
or return ()
at the end. So more explicitly written, your code behaves like:
func newFunc() -> Void {
print("I print a message")
return ()
}
print("Function said: \(newFunc())")
From here, hopefully it should be clear why you're getting the result you're seeing.
What you probably want to do instead is have newFunc()
return a useful value, and have that interpolated into your string. Like so:
func newFunc() -> String {
return "I print a message" // Actually, no you don't, you return a message.
}
print("Function said: \(nenFunc())")
Upvotes: 1
Reputation: 59
I think looking at call stacks will help you understand this concept more. Essentially, when you make a call to your main method (the alone print statement), main() get's placed on the stack. When a function is on the stack, it is not popped until it has been run to completion. Since your call to newFunc() happens before main completes, newFunc is then placed on top of main in the call stack. newFunc() prints, completes, and is popped. Thus, main does the same.
If the question is "why doesn't the output look like Function said: I print a message
?", then the simple solution is to change the code to the following
func newFunc() {
return "I print a message"
}
print("Function said: \(newFunc())")
Here you'll see the newFunc() method does not print anything but rather returns a value to its caller, main().
Upvotes: 0