我有一组Business对象。每个Business对象都包含一个键值对数组,其中一个元素可以是ContentBlocks对象的嵌套数组。
var masterArray = [
Business(busName: "Dave's Cafe", busId: 1, website: "http://www.davescafe.com", latLong: (45.541, -45.609),
actions: [["title": "About Us", "contentId": "123", "actionType": "content"],
["title": "Website", "url": "http://www.davescafe.com", "actionType": "web"]],
contentBlocks:[
ContentBlock(busName: "Dave's Cafe", busId: 1, contentId: "123", title: "Testola!", body: "Hello there!")
]),
Business(busName:...
]
我可以使用以下内容过滤数组以返回与唯一busId
匹配的特定商家:
let rtnArray = masterArray.filter{$0.busId == id}
if rtnArray.count == 1{
return rtnArray[0]
} else {
return // feedback that no matches were found
}
此外,我想通过过滤唯一的contentId
来返回特定的contentBlock(如果有必要,我也可以通过商家'{owner}'的busId
)。我真的很努力向前迈进,所以任何正确方向的指针都会很棒。
答案 0 :(得分:4)
以下是我认为您要问的解决方案:
var contentBlocks = masterArray
.flatMap{$0.contentBlocks}
.flatMap{$0}
.filter{$0.contentId == "123"}
从所有[ContentBlock]
个对象中输出包含与过滤器匹配的所有ContentBlock
个对象的Business
。
Business
es列表变为[ContentBlock?]
[ContentBlock?]
展平为[ContentBlock]
[ContentBlock]
已过滤答案 1 :(得分:1)
试试这个:
// The busId and contentId you want to find
let busId = 1
let contentId = "123"
let contentBlocks = masterArray.flatMap {
$0.contentBlocks.filter { $0.busId == busId && $0.contentId == contentId }
}
答案 2 :(得分:0)
在处理模型时,要搜索类的嵌套自定义对象。
这是课程示例。
public final class Model1 {
// MARK: Properties
public var firstname: String?
public var lastname: String?
public var email: String?
public var availabilities: [Availability]?
public var username: String?
}
public final class Availability {
var date: String
var day : String
init(date: String, day: String) {
self.date = date
self.day = day
}
}
public final class AvailData {
var am: String?
var pm: String?
init(am: String?,pm: String?) {
self.am = am
self.pm = pm
}
}
创建一个Model1数组。
var arrData = [Model1]()
对于我来说,我想搜索可用性数组。因此,我将逻辑放在下面,它可以正常工作。
let searchData = arrData.filter({ singleObj -> Bool in
let result = singleObj.availabilities?.filter({ $0.date == "2019/09/17" })
return result?.count > 0 ? true : false
})
此快速代码将仅返回与2019/09/17
匹配的那些记录