Returning values from a function returning `Void` should be avoidedSW-R1014
Returning values from a function that is declared to return Void
is
unnecessary and can lead to confusion and potential bugs in the code. Here are
a few reasons why returning values from a Void
function should be avoided:
Ambiguity: When a function is declared to return Void
, it indicates that the
function does not produce any value. However, if a value is returned from such
a function, it creates ambiguity and makes it unclear what the purpose of the
returned value is. This can confuse other developers who read and maintain the
code, leading to potential misunderstandings and bugs.
Expectations: Functions that return Void
are typically used for performing
side effects or actions without returning any result. By returning values from
a Void
function, it sets up expectations that the returned value will be used
or have some significance, which goes against the intended purpose of the
function. This can lead to incorrect assumptions and incorrect usage of the
returned value.
To fix this issue, remove the return statement from the Void
function. If the
function needs to return a value, update its return type accordingly. Here's an
example:
Bad Practice
func doSomething() -> Void {
// ...
return 42
}
Recommended
func doSomething() -> Int {
// ...
return 42
}
// OR
func doSomething() -> Void {
// ...
}