快速提问…我正在制作一个婴儿名应用程序,并试图过滤由用户选择的结果。我设法让它工作,但它需要一段时间的结果过滤。我是说2-3秒。
我写的是:
func apply(list: [String]) -> [String] {
let allSavedSettings = settings.all
var newList = list
if let short = allSavedSettings["short"] as? Bool {
if !short {
print("filter short")
newList = newList.filter({$0.count > 4})
}
}
if let long = allSavedSettings["long"] as? Bool {
if !long {
print("filter long")
newList = newList.filter({$0.count < 5})
}
}
if let dutch = allSavedSettings["dutch"] as? Bool {
if !dutch {
print("filter dutch")
newList = newList.filter({!dutchboy.contains($0)})
newList = newList.filter({!dutchgirl.contains($0)})
}
}
if let english = allSavedSettings["english"] as? Bool {
if !english {
print("filter english")
newList = newList.filter({!englishboy.contains($0)})
newList = newList.filter({!englishgirl.contains($0)})
}
}
if let arabic = allSavedSettings["arabic"] as? Bool {
if !arabic {
print("filter arabic")
newList = newList.filter({!arabicboy.contains($0)})
newList = newList.filter({!arabicgirl.contains($0)})
}
}
if let hebrew = allSavedSettings["hebrew"] as? Bool {
if !hebrew {
print("filter hebrew")
newList = newList.filter({!hebrewboy.contains($0)})
newList = newList.filter({!hebrewgirl.contains($0)})
}
}
if let latin = allSavedSettings["latin"] as? Bool {
if !latin {
print("filter latin")
newList = newList.filter({!latinboy.contains($0)})
newList = newList.filter({!latingirl.contains($0)})
}
}
if let chinese = allSavedSettings["chinese"] as? Bool {
if !chinese {
print("filter chinese")
newList = newList.filter({!chineseboy.contains($0)})
newList = newList.filter({!chinesegirl.contains($0)})
}
}
if let scandinavian = allSavedSettings["scandinavian"] as? Bool {
if !scandinavian {
print("filter scandinavian")
newList = newList.filter({!scandinavianboy.contains($0)})
newList = newList.filter({!scandinaviangirl.contains($0)})
}
}
if let spanish = allSavedSettings["spanish"] as? Bool {
if !spanish {
print("filter spanish")
newList = newList.filter({!spanishboy.contains($0)})
newList = newList.filter({!spanishgirl.contains($0)})
}
}
return newList
}
因此,我将用户偏好保存为布尔值,保存在名为"allSavedSettings"userdefaults。当设置为false时,它将从完整的名称列表中过滤结果。
我应该用什么别的东西来加快速度吗?这个名单大约有5000个名字。
提前感谢。
帕特里克
我尽可能使用集合,因为散列比在数组上多次迭代要快,而且它消除了重复。您不需要将主列表转换为集合,因为那样会增加额外的循环。
这样的东西应该会加快速度。
var doNotInclude = Set<String>()
if allSavedSettings["english"] == false {
doNotInclude.formUnion(Set(englishBoy + englishGirl))
}
if allSavedSettings["dutch"] == false {
doNotInclude.formUnion(Set(dutchBoy + dutchGirl))
}
if allSavedSettings["arabic"] == false {
doNotInclude.formUnion(Set(arabicBoy + arabicGirl))
}
let result = list.filter { !doNotInclude.contains($0) }