Start learning free

LESSON 71 OF 415 · CONDITIONAL STATEMENTS

Is Number Negative in Swift: if and else

Practice Read the full explanation

Create a function that takes a number n as its only argument and prints "negative" to the console if n is less than zero, otherwise prints "positive" to the console.

Example 1:

Input: n = 5
Output: "positive"
Explanation:
5 is greater than or equal to zero, so our function prints "positive" to the console.

Example 2:

Input: n = 0
Output: "positive"
Explanation:
0 is greater than or equal to zero, so our function prints "positive" to the console.

Example 3:

Input: n = -2
Output: "negative"
Explanation:
-2 is less than zero, so our function prints "negative" to the console.

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 positive.
STEP 1 OF 3
    Ctrl + Enter to check

    SWIFT · CONDITIONAL STATEMENTS

    Is Number Negative in Swift, explained

    Problem overview

    The method isNegative takes an integer n and prints a word to the console: negative when n is less than zero, and positive otherwise. It doesn't return anything.

    Three examples show the rule. For n = 5 it prints positive. For n = -2 it prints negative. For n = 0 it prints positive, because zero is not below zero. The word "positive" here really means "zero or greater", so zero lands on the positive side.

    Approach

    The question has two possible answers, and the decision depends on one comparison: is n < 0? That is exactly what an if-else statement is for. If the comparison is true, run one block; if it is false, run the other.

    The strict < matters. With n <= 0, zero would be reported as negative. With n > 0 as the test for "positive", zero would fall into the other branch. Testing n < 0 and letting else take everything else gives the right answer for all three examples.

    Step by step

    1. Write the if with its condition. The condition is n < 0. Swift needs no parentheses around it, but the braces after it are required. At this stage the body can stay empty.
    2. Print inside the if. Add print("negative") between the braces. The quotes make it a string, and print ends the output with a line break.
    3. Add the else. It has no condition: it runs whenever n < 0 is false, which covers zero and every positive number. It prints "positive".

    The solution in Swift

    class Solution {
        func isNegative(_ n: Int) {
            if n < 0 {
                print("negative")
            } else {
                print("positive")
            }
        }
    }
    

    Swift details worth knowing:

    • The underscore in _ n: Int means the caller doesn't write a label. You call isNegative(5), not isNegative(n: 5).
    • No return type. The signature has no ->, so the method returns nothing and its only effect is the output. Trying to use its result is pointless: let r = s.isNegative(3) gives r the empty tuple type (), and the compiler warns that this "may be unexpected".
    • Calling it. The method belongs to a class, so create an instance first. After let s = Solution(), the call s.isNegative(-2) prints negative.
    • Int only. The parameter is an Int, so the comparison with the literal 0 needs no conversion. A Double argument would not compile.

    Edge cases and common mistakes

    • Zero. isNegative(0) prints positive. Using <= by mistake would print negative.
    • Printing versus returning. This method prints. If the output has to be a value your code can use later, the method would need a return type, as in the next lessons of this chapter.
    • Mismatched words. The output must be exactly negative or positive, in lowercase, with no extra text.
    • Printing both. Without the else, writing a second print("positive") after the if would run for negative numbers too. The else keeps the two outcomes exclusive.
    • A condition that isn't a Bool. Swift rejects tests like if n {, so the comparison is always spelled out.

    Testing

    • isNegative(5) prints positive.
    • isNegative(0) prints positive.
    • isNegative(-2) prints negative.
    • isNegative(-1) prints negative, the closest negative value to the boundary.
    • isNegative(1) prints positive, the closest positive value.
    Keep going with SwiftAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free