我在 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 作为模型对象。使用 structs
、classes
和 enums
是非常可靠的。
因此,您的模型看起来类似于:
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/