Using void functions with ternary operators can lead to unexpected behavior and should be avoided.
When using a ternary operator, there must be a return value in both cases. If a void function is used as one of the return values, the function will be executed but the result will not be used. This can lead to confusion for other developers reading the code, as it may not be clear what the intended behavior is.
Additionally, using a void function in a ternary operator can make it harder to reason about the code and can introduce bugs. For example, if the void function has side effects, it may be executed even if the other branch of the ternary operator is taken.
To fix this issue, use functions that return a value instead of void functions when using a ternary operator.
func doSomething() {
print("This function does something")
}
let result = someCondition ? doSomething() : ""
func returnSomething() -> String {
return "This function returns something"
}
let result = someCondition ? returnSomething() : ""