我有一类名为“EpisodeInfoData”的属性
class EpisodeInfoData {
var episodeId = ""
var episodeName = ""
}
我将这些类的对象存储到一个字典中,其第一个元素是“String”,另一个元素是“EpisodeInfoData”类对象的数组
var episodes = Dictionary<String, [EpisodeInfoData]>()
let infoObj1 = EpisodeInfoData()
infoObj1.episodeId = "1"
infoObj1.episodeName = "one"
let infoObj2 = EpisodeInfoData()
infoObj2.episodeId = "2"
infoObj2.episodeName = "two"
let infoObj3 = EpisodeInfoData()
infoObj3.episodeId = "3"
infoObj3.episodeName = "three"
let infoObj4 = EpisodeInfoData()
infoObj4.episodeId = "4"
infoObj4.episodeName = "four"
let infoObj5 = EpisodeInfoData()
infoObj5.episodeId = "5"
infoObj5.episodeName = "five"
let infoObj6 = EpisodeInfoData()
infoObj6.episodeId = "6"
infoObj6.episodeName = "six"
let infoObj7 = EpisodeInfoData()
infoObj7.episodeId = "7"
infoObj7.episodeName = "seven"
let infoObj8 = EpisodeInfoData()
infoObj8.episodeId = "8"
infoObj8.episodeName = "eight"
episodes["season1"] = [infoObj1,infoObj2,infoObj3,infoObj4]
episodes["season2"] = [infoObj5,infoObj6,infoObj7,infoObj8]
我希望在“剧集”词典中获得季节名称,其剧集名称为“8”。我试着在它上面应用过滤器它没有用。
任何人都可以建议我使用过滤器查找结果而不使用过滤器。
提前谢谢
答案 0 :(得分:1)
不得不添加另一个答案,感谢那些在没有真正帮助的情况下投票的人。
试试这个
if let episode = (episodes.filter { $0.1.contains { $0.episodeName == "eight" } }).first {
print(episode.0) // season2
}
答案 1 :(得分:0)
struct EpisodeInfoData {
let episodeId: String
let episodeName: String
}
let episodes = [
"season1": [
EpisodeInfoData(
episodeId: "1",
episodeName: "one"
),
EpisodeInfoData(
episodeId: "2",
episodeName: "two"
),
EpisodeInfoData(
episodeId: "3",
episodeName: "three"
),
EpisodeInfoData(
episodeId: "4",
episodeName: "four"
),
],
"season2": [
EpisodeInfoData(
episodeId: "5",
episodeName: "five"
),
EpisodeInfoData(
episodeId: "6",
episodeName: "six"
),
EpisodeInfoData(
episodeId: "7",
episodeName: "seven"
),
EpisodeInfoData(
episodeId: "8",
episodeName: "eight"
)
]
]
let desiredName = "eight"
let result = episodes.filter{ _, seasonEpisodes in
return seasonEpisodes.contains{ $0.episodeName == desiredName }
}.map{ key, value in return key}
print(result)
首先过滤剧集字典。仅当值(seasonEpisodes
数组)包含具有desiredName
的剧集时,才会保留字典中的键值对。然后,映射这些键值对,并仅返回键(季节名称)。