假设我有如下数据。
[
{
hotelName : "Hotel 1",
hotelType : 1
prices :
[
{
roomType: "Single Room",
price : 1231
},
{
roomType: "Twin Room",
price : 1232
},
{
roomType: "Triple Room",
price : 1233
},
]
},
{
hotelName : "Hotel 2",
hotelType : 2
prices :
[
{
roomType: "Single Room",
price : 1241
},
{
roomType: "Twin Room",
price : 1242
},
{
roomType: "Triple Room",
price : 1243
},
]
}
]
我想要的是用价格过滤酒店。
假设我想过滤以获取低于范围的酒店。
价格范围为 1231-1233 >> 这将仅返回酒店 1。
价格范围为 1231-1431 >> 这将返回酒店 1 和酒店 2。
我有相同类型的过滤器,但我只有 1 个价格,所以我所做的如下。
finalArray = finalArray.filter() {
CGFloat(($0.prices![0].price)!) >= minValue
&&
CGFloat(($0.prices![0].price)!) <= maxValue
}
但是现在我有一系列价格,所以我不确定在这种情况下如何处理。
问题在行
$0.prices![0].price
^^^
有人可以为我指出正确的方向来实现这个过滤器吗?
最佳答案
你可以这样做:
struct Price {
let roomType: String
let price: Double
}
struct Hotel {
let hotelName: String
let hotelType: Int
let prices: [Price]
}
let hotel1 = Hotel(hotelName: "Hotel 1", hotelType: 1, prices: [
Price(roomType: "Single Room", price: 1231),
Price(roomType: "Twin Room", price: 1232),
Price(roomType: "Triple Room", price: 1233)
])
let hotel2 = Hotel(hotelName: "Hotel 2", hotelType: 1, prices: [
Price(roomType: "Single Room", price: 1241),
Price(roomType: "Twin Room", price: 1242),
Price(roomType: "Triple Room", price: 1243)
])
func getHotelsInRange(_ hotels: [Hotel],
from min: Double,
to max: Double) -> [Hotel] {
return hotels.filter { h in
h.prices.contains{ p in
switch p.price {
case min...max:
return true
default:
return false
}
}
}
}
let result = getHotelsInRange([hotel1, hotel2], from: min, to: max)
关于swift - 当我们有内部数组并且需要对内部数组应用过滤器时如何过滤数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50604000/