Start learning free

LESSON 73 OF 415 · CONDITIONAL STATEMENTS

Return Negative in Swift: Returning a Value from if-else

Practice Read the full explanation

Create a function that takes a number as an argument and returns negative of that number. Return negative numbers without any change.

Examples:

4 ➞ -4

15 ➞ -15

-4 ➞ -4

0 ➞ 0

Hints:

You can make use of < operator with an if statement to check if n is negative.

You can add an else statement to handle the case when n is not negative.
STEP 1 OF 3
    Ctrl + Enter to check

    SWIFT · CONDITIONAL STATEMENTS

    Return Negative in Swift, explained

    Problem overview

    The method negative takes an integer n and returns the negative of that number. A number that is already negative comes back unchanged.

    negative(4)   gives -4
    negative(15)  gives -15
    negative(-4)  gives -4
    negative(0)   gives 0
    

    This differs from the previous exercise because the method returns a number instead of printing a word. The caller gets a value it can use in further calculations.

    Approach

    There are two cases. If n is below zero, it already has the right sign, so return it as it is. Otherwise n is zero or positive, and putting a minus sign in front of it gives the value we want. The unary minus -n flips the sign of a positive number, and -0 is still 0, so zero needs no special case.

    A tempting shortcut is to always return -n. It works for 4 and 15, but for -4 it returns 4, which is the wrong sign. The condition is what stops the method from turning negative numbers positive.

    Step by step

    1. Write the if. The condition is n < 0, which means the input is already negative.
    2. Return n inside it. The return statement hands the value back and ends the method on the spot.
    3. Add the else branch and return -n. It runs for zero and for positive inputs, where the unary minus produces the negative value.

    The solution in Swift

    class Solution {
        func negative(_ n: Int) -> Int {
            if n < 0 {
                return n
            } else {
                return -n
            }
        }
    }
    

    Swift details worth knowing:

    • The return type. -> Int promises that the method gives back an Int. Every possible path through the method must then end in a return. Here both branches do, so the compiler is satisfied.
    • A missing return is an error. If you write only the if branch, the compiler stops with missing return in instance method expected to return 'Int', because a non-negative n would reach the end without returning anything. That is why the starter code, with an empty body, doesn't compile until the method returns something on every path.
    • Unary minus. -n is an expression that produces a new value. It doesn't change n, which is a constant inside the method, as all parameters are in Swift.
    • Calling it. After let s = Solution(), the call s.negative(15) returns -15, and print(s.negative(-4)) prints -4.
    • The underscore in _ n: Int means callers write negative(15) without a label.

    Edge cases and common mistakes

    • Zero. negative(0) goes to the else branch and returns -0, which is the integer 0. Integers have no negative zero in Swift.
    • Printing instead of returning. print(-n) shows a number on the console but gives the caller nothing. The tests check the returned value.
    • Using n <= 0. The result stays correct, because both branches give 0 for zero, but the strict comparison states the intent better.
    • Returning abs(n) or flipping the wrong case. The absolute value is the opposite of what the task asks.
    • Largest values. negative(Int.max) returns -9223372036854775807, which fits in an Int.

    Testing

    • negative(4) returns -4.
    • negative(15) returns -15.
    • negative(-4) returns -4.
    • negative(0) returns 0.
    Keep going with SwiftAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free