gpt4 book ai didi

ios - 使用 Swift 匹配 NSArray 中的 NSDictionary 的模式

转载 作者:搜寻专家 更新时间:2023-11-01 06:10:20 24 4
gpt4 key购买 nike

我在 Playground 上有这段代码

import UIKit

let anArray = NSArray(array:[["code": "LT","name": "Lithuania"], ["code": "ME","name": "Montenegro"], ["code": "ES","name": "Spain"]])

let findCode = "ES"

for object in anArray {
if (object["code"] as String == findCode) {
object["name"] as String
}
}

我想通过模式匹配以某种方式简化它,这可能吗?

最佳答案

这是我在 Playground 上创建的...

import UIKit

let array : [[String: String]] = [["code": "LT","name": "Lithuania"], ["code": "ME","name": "Montenegro"], ["code": "ES","name": "Spain"]]

let findCode = "ES"

let filteredArray = array.filter{$0["code"] == findCode}

println(filteredArray) // [["code": "ES", "name": "Spain"]]

它使用过滤函数而不是迭代。

filteredArray 将是一个对象数组,其中 object["code"] == findCode

编辑 - 如果您知道只有一个

...
let foundObject = array.filter{$0["code"] == findCode}.first

println(foundObject) // ["code": "ES", "name": "Spain"]

你可以通过做...走得更远

...
let country = array.filter{$0["code"] == findCode}.first?["name"] // updated, thanks @MikeS

if let unwrappedCountry = country {
println(unwrappedCountry) // "Spain"
}

关于ios - 使用 Swift 匹配 NSArray 中的 NSDictionary 的模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26657766/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com