0

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)
}

2 Answers 2

2

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

let searchTerm = "Mango"
if fruitArray.contains(searchTerm) {
    print(searchTerm)
}
Sign up to request clarification or add additional context in comments.

Comments

1

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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.