About Return Values and return - Images: Japanese
Hey there, everyone!
Alright, let's keep things moving — today we're covering 'return' and 'return values'.
We've been going over how to define functions, but here's something we haven't touched on yet: functions can actually return something when they're called.
Not totally sure what that means? Here's a scenario: say you want to take a value passed in as an argument, do something with it, and then store the result in a variable. That's exactly where 'return' and 'return values' come in. Let's jump straight to a sample.
func test(n: Int) -> Int {
return n
}
let num = test(n: 10)
print(num) // Outputs the number '10'.
That's what using 'return' and a 'return value' looks like. Let's walk through the syntax as usual.
The 'func test(n: Int)' part is the same as before — nothing new there. What to focus on is what comes after it: '-> Int'. In Swift, you need to specify the data type of the value you want to return. You do that with the '-> data type' syntax like above. Leave it out and you'll get an error, so watch out.
func test(n: Int) { // Error — missing '-> data type'.
return n
}
Once you've specified the return type, write 'return' inside the function body, followed by a space and the value you want to return.
Here's what it looks like when you want to "return a string received as an argument as-is":
func test(s: String) -> String {
return s
}
let str = test(s: "Hatsune Miku") // The string returned by the function 'test' is stored in the constant 'str'.
print(str) // Outputs the string 'Hatsune Miku'.
One more thing to keep in mind: if you write '-> data type' but the function doesn't actually return anything, that's also an error. Be careful with that.
func test(s: String) -> String { // Error — you declared a return type, so you need to actually return something.
}
That covers the basics. By the way, you can also put an expression on the right side of 'return'. In the example below, the result of 'n + _n' is what gets returned.
func test(n: Int, _n: Int) -> Int {
return n + _n // Expressions work here too.
}
let num = test(n: 10, _n: 20)
print(num) // Outputs the number '30'.
Now let's go over a few more advanced uses.
First up: when 'return' is hit, the function stops executing right there. Take a look at this sample.
func test(n: Int) -> Int {
return n // Execution stops here.
print(n) // This line never runs.
}
let num = test(n: 10)
print(num) // Outputs the number '10'.
Notice the 'print(n)' line. Because 'return n' comes before it, the function ends right there — so 'print(n)' never gets a chance to run.
This behavior is really useful, so make sure you've got it down.
And just so you know, you can use 'return' this way in functions that don't return a value too. Like this:
func test() {
return; // Execution stops here.
print("Hatsune Miku") // This line never runs.
}
test()
Even though we haven't written '-> data type' here, using 'return' on its own still exits the function early.
There's one thing to watch out for in this pattern. Notice how 'return' in the example above has a semicolon after it — 'return;'.
In Swift, you can use ';' to mark the end of a statement. Without it here, Swift would interpret 'print("Hatsune Miku")' as the thing being returned — and that line would actually execute.
func test() {
return // No semicolon.
print("Hatsune Miku") // This gets treated as what's being returned, so it runs.
}
test() // Outputs the string 'Hatsune Miku'.
The reason: 'return' will return whatever follows it — whether separated by a space or a newline. So the behavior above is the result of that rule.
It's a bit tricky if you're not used to it yet, so be careful not to trip up here.
Next, let's look at returning arrays or dictionaries.
We haven't shown examples of passing arrays or dictionaries as arguments yet, so let's start there. Here's how it looks:
func test(arr: [Int]) { // Accepts an array of Int values.
print(arr)
}
func test1(dic: [String: Int]) { // Accepts a dictionary with String keys and Int values.
print(dic)
}
test(arr: [0, 1, 2]) // Outputs '[0, 1, 2]'.
test1(dic: ["Hatsune Miku": 0, "Lily": 1]) // Outputs '["Lily": 1, "Hatsune Miku": 0]'.
To accept an array, write the parameter as 'paramName: [DataType]' — like 'arr: [Int]'. For a dictionary, write it as 'paramName: [KeyType: ValueType]' — like 'dic: [String: Int]'.
When calling the function, inside the parentheses you write 'paramName: arrayOrDictionary' — like 'arr: [0, 1, 2]'.
To return an array or dictionary, the syntax is the same as before. Use '-> [DataType]' for an array and '-> [KeyType: ValueType]' for a dictionary. Here's what that looks like:
func test(arr: [Int]) -> [Int] { // Returns an array of Int values.
return arr
}
func test1(dic: [String: Int]) -> [String: Int] { // Returns a dictionary with String keys and Int values.
return dic
}
let a = test(arr: [0, 1, 2]) // Stores '[0, 1, 2]'.
let d = test1(dic: ["Hatsune Miku": 0, "Lily": 1]) // Stores '["Lily": 1, "Hatsune Miku": 0]'.
print(a) // Outputs '[0, 1, 2]'.
print(d) // Outputs '["Lily": 1, "Hatsune Miku": 0]'.
So that's the rundown on the basics of 'return' and return values.
Here's one more advanced trick: by using '()', you can return multiple values at once. This is known as a 'tuple'.
func test(n: Int, s: String) -> (Int, String) {
return (n, s)
}
let tpl = test(n: 10, s: "Hatsune Miku")
print(tpl) // Outputs '(10, "Hatsune Miku")'.
In the next article, we'll dig into 'tuples' properly. That's all for now — see you there!
This article was written by Sakurama.
Author's beloved small mammal |
桜舞 春人 Sakurama HarutoA Tokyo-based programmer who has been creating various content since the ISDN era, with a bit of concern about his hair. A true long sleeper who generally feels unwell without at least 10 hours of sleep. His dream is to live a life where he can sleep as much as he wants. Loves games, sports, and music. Please share some hair with him. |
If you find any errors or copyright issues, please contact us.