Cryptic
Cryptic

Reputation: 37

How do I search an array of strings and return a specific value in swift?

I'm new to swift and I'm trying to search an array of strings and return a specific value, for example let's say i want to search my array and check if contains mango, if it does then I would like to print that.

var fruitArray: Array = ["Banana", "Apple", "Mango", "Strawberry", "blueberry"]
fruitArray.append("Orange")
for fruits in fruitArray{
    print(fruits)
}

Upvotes: 0

Views: 240

Answers (2)

Leo Dabus
Leo Dabus

Reputation: 236508

You can use collection's method firstIndex(of:) to find the index of the element on your collection and access the element through subscript or if the index of the element is irrelevant you can use first(where:) to find the first element that matches your element or any predicate you may need:

var fruits = ["Banana", "Apple", "Mango", "Strawberry", "blueberry"]
fruits.append("Orange")

if let firstIndex = fruits.firstIndex(of: "Mango") {
    print(fruits[firstIndex])  // Mango
    // if you need to replace the fruit
    fruits[firstIndex] = "Grape"
    print(fruits) // "["Banana", "Apple", "Grape", "Strawberry", "blueberry", "Orange"]\n"
}

or

if let firstMatch = fruits.first(where: { $0.hasSuffix("go")}) {
    print(firstMatch)  // Mango
}

Upvotes: 1

Marc
Marc

Reputation: 3070

You don't need to iterate over the array yourself.

let searchTerm = "Mango"
if fruitArray.contains(searchTerm) {
    print(searchTerm)
}

Upvotes: 2

Related Questions