Start learning free

LESSON 114 OF 678 · ARRAYS I

Checking an Array for a Value in Swift with contains

Lesson Read the full explanation

TL ; DR:

arr.contains(x) is true when the array holds x, and false when it doesn't. Use it as the condition of an if.


let colors = ["red", "green", "blue"]

print(colors.contains("red"))    // true
print(colors.contains("pink"))   // false

if !colors.contains("pink") {
    print("No pink yet")
}


Full lesson:

Often you need to know if an array holds some value. Is this name on the guest list? Is this item in the cart?

contains(x) answers that. It compares each item with x, from the first one on. It returns true as soon as one matches, or false if none does.

Put ! in front for the opposite. So !colors.contains(x) is true when x is missing.

The answer is a Bool, so it fits right into an if:

let cart = ["milk", "bread"]

if cart.contains("milk") {
    print("Milk is in the cart")
}

As with any Swift if, the condition needs no parentheses. The ! goes right before the array's name.

Text must match exactly. So colors.contains("Red") is false, because the array has "red".


Your task

bag holds what is packed for a hike.

If "water" is in bag, print Water is packed. If "tent" is not in bag, print Pack a tent.

Expected output:

Water is packed
Pack a tent
STEP 1 OF 2
    Ctrl + Enter to check

    SWIFT · ARRAYS I

    Array Membership in Swift, explained

    The question contains answers

    Often a program needs to know whether an array holds some value. Is this name on the guest list? Is this item in the cart? In Swift the method for that is contains. It compares the items with the value you pass, from the first item on, and returns a Bool: true as soon as one matches, false if none does.

    let colors = ["red", "green", "blue"]
    
    print(colors.contains("red"))
    print(colors.contains("pink"))
    
    true
    false
    

    Using it in an if

    Because the answer is a Bool, it works directly as the condition of an if. Swift needs no parentheses around the condition:

    let cart = ["milk", "bread"]
    
    if cart.contains("milk") {
        print("Milk is in the cart")
    }
    

    For the opposite question, put ! in front. !cart.contains("eggs") is true when "eggs" is missing. The ! goes right before the array's name, and it applies to the whole call.

    if !cart.contains("eggs") {
        print("Buy eggs")
    }
    

    The two forms can be combined with an else when both outcomes need a reaction:

    if cart.contains("eggs") {
        print("Eggs are in the cart")
    } else {
        print("No eggs yet")
    }
    
    No eggs yet
    

    A good habit is to read the condition aloud: "if the cart contains eggs" or "if not the cart contains eggs". If it sounds right, the code almost always does what you meant.

    What contains does for you

    You could write the same check by hand with a loop and a flag:

    let bag = ["map", "water", "snacks"]
    var found = false
    for item in bag {
        if item == "water" {
            found = true
            break
        }
    }
    print(found)
    
    true
    

    contains is that loop in one call. It stops at the first match, so it doesn't look at the items after it. When nothing matches, it has to look at every item, so a longer array takes longer to answer "no".

    The answer reflects the array at the moment you ask. If the array changes later, ask again:

    var names = ["Ana", "Ben"]
    print(names.contains("Cleo"))
    names.append("Cleo")
    print(names.contains("Cleo"))
    
    false
    true
    

    Things to watch

    • Text must match exactly. Upper and lower case count, so contains("Red") is false for an array that holds "red".
    • Whole items, not parts. ["water bottle"].contains("water") is false: contains compares one full item at a time.
    • An empty array contains nothing, so the answer is always false.
    • Other types work too. [3, 8, 1].contains(8) is true. For your own types, they have to be comparable with ==.
    • Testing a rule instead of a value. contains(where:) takes a closure: [3, 8, 1].contains(where: { $0 > 5 }) is true, because 8 is bigger than 5.

    The exercise: packing a bag

    bag holds ["map", "water", "snacks"]. The task has two checks. First, if "water" is in the bag, print Water is packed:

    if bag.contains("water") {
        print("Water is packed")
    }
    

    The bag does have water, so the condition is true and the print runs. Second, if "tent" is not in the bag, print Pack a tent. Here contains gives false, and the ! turns that into true:

    if !bag.contains("tent") {
        print("Pack a tent")
    }
    

    The full program:

    let bag = ["map", "water", "snacks"]
    if bag.contains("water") {
        print("Water is packed")
    }
    if !bag.contains("tent") {
        print("Pack a tent")
    }
    
    Water is packed
    Pack a tent
    

    A common slip is to write if bag.contains("tent") when the task says the tent is missing. The bag has no tent, so that condition is false and nothing prints. When the task says "is not in", reach for the !.

    Key takeaways

    • arr.contains(x) returns true or false.
    • Use it as an if condition, with no parentheses.
    • !arr.contains(x) means "x is missing".
    • Matching is exact, including letter case.
    Keep going with Swift500+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free