Swift中带返回值与无返回值函数的核心差异是什么?
Hey there! Let's break down the difference between functions with return values and those without in Swift, then dive into the two examples you shared.
带返回值 vs 无返回值函数的核心差异
In Swift, these two function types serve distinct purposes:
- 无返回值函数(隐式返回Void): These functions are built to handle side effects — like printing to the console, modifying external variables, updating UI, or triggering an action. Even if you don’t write a return type, Swift automatically makes them return
Void(an empty tuple()). Their main job is to "do something," not to pass data back to the caller. - 带返回值函数: These functions exist to compute and deliver data. You declare their return type with
-> Type, and they must return a value of that type (either explicitly withreturnor implicitly for single-expression functions). The caller can then use this returned value for further work: assign it to a variable, pass it to another function, or include it in calculations. They often prioritize producing a result over causing side effects.
你的两个示例函数的核心区别
Let’s break down each function to see their key differences:
1. func sqr(number: Int) { print (number * number) }
This is a typical void-return function:
- It has no declared return type, so it implicitly returns
Void. - Its only job is to perform a side effect: directly printing the squared value to the console.
- When you call it (e.g.,
sqr(number: 5)), you can’t capture the squared value for later use. Even if you trylet result = sqr(number: 5),resultwill just be()— useless for any numerical operations.
2. func sqr1(number: Int) -> Int { return number * number }
This is a value-returning function:
- It explicitly states it returns an
Int, so it must send back a squared integer viareturn. - Its core responsibility is to compute and deliver the squared value — no side effects are baked into this function (unless you add them, which this example doesn’t).
- When you call it, you’re in full control of the result:
let squared = sqr1(number: 5) // squared holds the value 25 print(squared) // You choose to print it if needed let total = squared + 15 // Or use it in another calculation
The big-picture difference is responsibility separation:
sqrties computation and output into a single function.sqr1focuses only on computation, leaving the decision of what to do with the result (print, store, etc.) entirely up to the caller.
内容的提问来源于stack exchange,提问作者Ian Solomein
相关产品推荐
相关产品推荐

