arrays - 检查值是否与自定义数组元素列表中的键匹配并检索其值

标签 arrays swift dictionary filter

我在 Swift 中有两个自定义数据数组。我想找到包含字典值的对象,其“目的地”等于第二个数组中的“PlaceId”。这是带有一些数据的结构,只是为了展示它们的外观。

struct FlightInfo {
var minPrice = "648"
var carrier = "Canada Air ways"
var destination = "973973"
var origin = "983983"
}


struct PlaceData {
var cityName = "Melbourne"
var name = "Melbourne"
var cityId = "MEL"
var type = "blah"
var countryName = "Australia"
var placeId = 983983
}

到目前为止我得到了这个:

    let destId = flightsArray[indexPath.row].destination as String
    let results = listOfPlaces.filter { $0.placeId == Int(destId) }

但没有雪茄。我怎样才能得到像下面这样的最终结果:

cell.destinationLabel.text = results.placeID

最佳答案

首先,我会重新考虑使用 Dictionary 作为模型对象。使用 structsclassesenums 是非常可靠的。 因此,您的模型看起来类似于:

enum FlightType: String {
    case a = "A"
    case b = "B"
}

enum PlaceType: String {
    case station = "station"
    case port = "port"
}

struct Flight {
    var name: String
    var destinationId: Int
    var type: FlightType
}

struct Place {
    var identifier: Int
    var title: String
    var type: PlaceType
}

假设你有这样的数组:

let flights = [
    Flight(name: "Trenton", destinationId: 403, type: .a),
    Flight(name: "Houston", destinationId: 288, type: .a),
    Flight(name: "Boston", destinationId: 244, type: .a)
]

let places = [
    Place(identifier: 111, title: "Leslie", type: .station),
    Place(identifier: 228, title: "Mary", type: .station),
    Place(identifier: 684, title: "Joe", type: .station),
    Place(identifier: 288, title: "Paul", type: .station),
    Place(identifier: 465, title: "Stephanie", type: .station),
    Place(identifier: 569, title: "Steve", type: .station),
    Place(identifier: 663, title: "Doug", type: .station)
]

您可以像这样获取航类的目的地标题:

let destinationId = flights[indexPath.row].destinationId
let destinationTitle = places.filter{ $0.identifier == destinationId }.first?.title

关于arrays - 检查值是否与自定义数组元素列表中的键匹配并检索其值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42345071/

相关文章:

javascript - 连接数组前缀和数组反转前缀的最佳方法

swift - 不能使用字符串类型的索引下标 NSDictionary 类型的值

swift - 结点并 swift 加入 Realm

iOS Core Graphic,如何计算CGAffineTransform(scaleX offset?

python - 在 cython 中创建小数组需要大量时间

c++ - 创建 2 个包含 2 个结构的数组。

php - 写入和提取数组

c# - 具有 3 个参数的哈希表

c# - 模型绑定(bind)字典

java - Map 的值是一个对象。我如何使用/迭代所有这些变量? ( java )