Start learning free

LESSON 130 OF 415 · LOOPS & CONDITIONALS

Print Positive Numbers From an Array in Swift: for-in and if

Practice Read the full explanation

Given an array of integers, print to the console the positive numbers, one on each line.

A number n is positive if it is strictly greater than 0.

Example:

Input: nums = [3, -2, 0, 4, -4]
Output (console):
3
4

Note: You have to print the numbers to the console, your function shouldn't return anything.


STEP 1 OF 3
    Ctrl + Enter to check

    SWIFT · LOOPS & CONDITIONALS

    Print Positive Numbers From Array in Swift, explained

    Problem overview

    The method printPositiveNumbers(_ nums: [Int]) receives an array of integers and prints the positive ones, one per line. A number is positive when it is strictly greater than 0, so 0 is not printed. The method returns nothing.

    For nums = [3, -2, 0, 4, -4] the output is 3 and then 4. The values -2 and -4 are negative, and 0 is neither positive nor negative.

    Approach: visit every element and filter

    The task combines two basic tools. A loop visits each element of the array, and a condition decides whether to print it. There is nothing to remember between elements, so no extra variables are needed, and the output keeps the order of the array.

    Step by step

    1. Loop over the array. A for-in loop over nums with the loop variable val gives one number per pass. The variable is created by the loop, so it is written without let or var.
    2. Check the sign. Inside the loop, an if tests val > 0. Use > and not >=, because zero must be left out.
    3. Print inside the if. A call to print(val) writes the number and a newline, so every positive number gets its own line.

    The solution in Swift

    class Solution {
        func printPositiveNumbers(_ nums: [Int]) {
            for val in nums {
                if val > 0 {
                    print(val)
                }
            }
        }
    }
    

    Swift details worth knowing:

    • Iterating an array. for val in nums goes through the elements in order. You don't need an index, and there is no way to go out of bounds.
    • A constant loop variable. val is a constant on every pass. Changing it inside the loop is a compile error, and changing it would not alter the array anyway, since the array is copied when passed in.
    • No parentheses, required braces. if val > 0 { ... } needs no parentheses around the condition, but the braces cannot be dropped.
    • Printing versus returning. The method returns Void. It writes to the console and the lesson's tests read that output.

    Other ways to write it

    Swift can put the condition in the loop header with a where clause. The body runs only for the elements that satisfy it:

    for val in nums where val > 0 {
        print(val)
    }
    

    Another version builds a filtered array first and loops over it, using filter with a closure:

    for val in nums.filter({ $0 > 0 }) {
        print(val)
    }
    

    Both print 3 and 4 for the example array. The lesson uses the plain loop and if, which makes each step visible. The filter version creates a second array in memory, so its extra space is O(n).

    Complexity

    Time: O(n), where n is the number of elements, because each element is looked at once.

    Space: O(1). The method creates no new collection.

    Edge cases and common mistakes

    • Zero. [0, 0] prints nothing, because 0 is not greater than 0. Using >= would print both zeros.
    • Empty array. The loop body never runs, so nothing is printed.
    • All negative. [-1, -5] prints nothing.
    • Printing the wrong thing. print("val") in quotes would print the word val. Without quotes it prints the number.
    • Returning a list. Building and returning an array of positives does not print anything.

    Testing

    • [3, -2, 0, 4, -4] prints 3 and 4.
    • [] prints nothing.
    • [0, 0] prints nothing.
    • [1, 2, 3] prints 1, 2 and 3.
    Keep going with SwiftAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free