要搜索结构中包含的字符串,我使用:
let results = myArray.filter( {$0.model.localizedCaseInsensitiveContains("bu")} )
但是说该结构有几个我想搜索的属性-也许我想一次搜索所有这些属性。我只能过滤基本类型,因此忽略“模型”将不起作用。
解决方案-------------------------
虽然我真的很喜欢下面Matt所建议的使用键路径的想法,但最终我在结构中添加了一个函数,使我的视图控制器代码更加简洁:
struct QuoteItem {
var itemIdentifier: UUID
var quoteNumber: String
var customerName: String
var address1: String
func quoteItemContains(_ searchString: String) -> Bool {
if self.address1.localizedCaseInsensitiveContains(searchString) ||
self.customerName.localizedCaseInsensitiveContains(searchString) ||
self.quoteNumber.localizedCaseInsensitiveContains(searchString)
{
return true
}
return false
}
然后,在我的控制器中,引号是QuoteItem的数组,我可以通过简单地编写以下内容来进行搜索:
searchQuoteArray = quotes.filter({ $0.quoteItemContains(searchString) })
答案 0 :(得分:2)
我希望我理解你的正确。我认为,通过这段代码,您可以实现所需的功能:
struct ExampleStruct {
let firstSearchString: String
let secondSearchString: String
}
let exampleOne = ExampleStruct(firstSearchString: "Hello", secondSearchString: "Dude")
let exampleTwo = ExampleStruct(firstSearchString: "Bye", secondSearchString: "Boy")
let exampleArray = [exampleOne, exampleTwo]
let searchString = "Hello"
let filteredArray = exampleArray.filter { (example) -> Bool in
// check here the properties you want to check
if (example.firstSearchString.localizedCaseInsensitiveContains(searchString) || example.secondSearchString.localizedCaseInsensitiveContains(searchString)) {
return true
}
return false
}
for example in filteredArray {
print(example)
}
这会在Playgrounds中打印以下内容:
ExampleStruct(firstSearchString: "Hello", secondSearchString: "Dude")
让我知道是否有帮助。
答案 1 :(得分:1)
这听起来像Swift的关键路径的工作。只需提供要搜索的String属性的关键路径即可。
struct MyStruct {
let manny = "Hi"
let moe = "Hey"
let jack = "Howdy"
}
let paths = [\MyStruct.manny, \MyStruct.moe, \MyStruct.jack]
let s = MyStruct()
let target = "y"
let results = paths.map { s[keyPath:$0].localizedCaseInsensitiveContains(target) }
// [false, true, true]