how to use where in swift

In Swift, you can use the where keyword with the filter function to apply a filter on an array. The filter function returns a new array that contains the elements that match the condition specified by the where clause.

Here is an example of using where in Swift:

main.swift
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

let filteredNumbers = numbers.filter { $0 % 2 == 0 }

print(filteredNumbers) // Output: [2, 4, 6, 8, 10]
152 chars
6 lines

In this example, we have an array of numbers from 1 to 10. The where clause in the filter function specifies that we want to keep only the numbers that are divisible by 2. The resulting filteredNumbers array will contain only the even numbers from the original array.

You can also use the where keyword with loops and other control flow statements in Swift.

gistlibby LogSnag