As both other answers point out, you're searching your array of results for an item with a value of "al". What you're wanting to is actually return an array of results, narrowed down to only those that match:
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 ]
Now then, again, for convenience, define a case insensitive contains function for String:
extension String {
func containsIgnoreCase(substring:String) -> Bool {
return rangeOfString(
substring,
options: .CaseInsensitiveSearch,
range: startIndex..<endIndex,
locale: nil)?.startIndex != nil
}
}
Note that String already has a contains function, it's just case sensitive, but if that's sufficient, you don't even need to define your own.
Now, you can use map to get rid of results that don't contain your search string:
searchResults = searchResults.map({
return SearchResult(
type: $0.type,
typeTitle: $0.typeTitle,
results: $0.results.filter({
$0.containsIgnoreCase("al")
})
)
})
And, presumably, you also want to eliminate any SearchResult with no actual results, so use filter:
searchResults = searchResults.filter { $0.results.count > 0 }
Of course, the whole thing can be strung into one expression:
searchResults = searchResults.map({
return SearchResult(
type: $0.type,
typeTitle: $0.typeTitle,
results: $0.results.filter({
$0.contains("al")
})
)
}).filter { $0.results.count > 0 }
And, you can possibly further reduce some of the iteration by using flatMap, which is like map, but eliminates any nil values:
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
}
}