正如其他答案指出的那樣,您正在搜索具有值「al」的項目的結果數組。什麼你想實際上是返回結果的數組,縮小到只有那些匹配:
struct SearchResult {
let type:String
let typeTitle:String
let results:[String]
}
let searchResultItem1 = SearchResult(
type: "contact",
typeTitle: "CONTACTS",
results: ["Joe" , "Smith" , "Alan" , "Nick" , "Jason"]
)
let searchResultItem2 = SearchResult(
type:"address",
typeTitle: "ADDRESS",
results:["829 6th Street North Fullerton" , "669 Windsor Drive Randallstown" , "423 Front Street Lacey"]
)
var searchResults = [ searchResultItem1, searchResultItem2 ]
現在,話又說回來,爲了方便,定義不區分大小寫包含函數的字符串:
extension String {
func containsIgnoreCase(substring:String) -> Bool {
return rangeOfString(
substring,
options: .CaseInsensitiveSearch,
range: startIndex..<endIndex,
locale: nil)?.startIndex != nil
}
}
請注意,字符串已經有一個contains
函數,它只是區分大小寫,但如果這是足夠的,你甚至不需要定義你自己的。現在
,您可以使用map
擺脫不包含搜索字符串的結果:
searchResults = searchResults.map({
return SearchResult(
type: $0.type,
typeTitle: $0.typeTitle,
results: $0.results.filter({
$0.containsIgnoreCase("al")
})
)
})
而且,想必,你也想消除沒有實際結果的任何信息搜索結果,所以使用過濾器:
searchResults = searchResults.filter { $0.results.count > 0 }
當然,整個事情可以串成一個表達:
searchResults = searchResults.map({
return SearchResult(
type: $0.type,
typeTitle: $0.typeTitle,
results: $0.results.filter({
$0.contains("al")
})
)
}).filter { $0.results.count > 0 }
而且,你都不可能再利用flatMap
,這就好比map
,但消除了任何nil
值減少一些重複的:
searchResults = searchResults.flatMap {
let results = $0.results.filter { $0.containsIgnoreCase("al") }
if results.count > 0 {
return SearchResult(type: $0.type, typeTitle: $0.typeTitle, results: results)
} else {
return nil
}
}
是的,你是對的。 – Nassif