-1

i want to print the name in world array which belong to continent: "europe"

    struct countries{
    let name: String
    let continent: String
}

var world: [countries] = [
    countries(name:"japan", continent: "asia"),
    countries(name:"france", continent: "europe"),
    countries(name:"italy", continent: "europe"),
    countries(name:"egypt", continent: "africa")
]
2

1 Answer 1

1
world.filter { $0.continent == "europe" }.forEach { print($0.name) }

If you want an array of Names:

world.filter { $0.continent == "europe" }.map { $0.name }
Sign up to request clarification or add additional context in comments.

4 Comments

what if i wanted the name to be returned as a string instead of printing it.
Updated the Answer :)
is it possible to update the world array to include only the filtered items or create a new array of the same type with the filtered items
let array = world.filter { ... } or: world = world.filter { ... }

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.