首页 > 解决方案 > 使用数组内容过滤数组

问题描述

我想在世界数组中打印属于大陆的名称:“欧洲”

    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")
]

标签: swift

解决方案


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

如果你想要一个名称数组:

world.filter { $0.continent == "europe" }.map { $0.name }

推荐阅读