请注意,我的问题仅针对 Swift 4 语法。我有笨重/大 字符串数组,我想过滤它以获取其中以某些特定字符/子字符串。这意味着我需要我的数组中的每个String匹配以一些子字符串开头。我找到了不同的链接,它为我提供了 Objective-C 的代码,我无法在 Swift 4 中实现它,因为 Swift 4 < / strong>即可。我通过在for循环中迭代我的数组手动解决了我的问题,但它给出了非常慢的结果所以我不想在这里使用任何循环,所以任何帮助都会有用。提前致谢。请参阅下面的代码:
func search() -> Void {
var dummyStringsArray:[String] = ["Hotel Restaurants","Restaurants","Certified Green Restaurant(R)","Japnies Food Restauarants","Grill Restaurants","Restaurant Equipment","Wholsale Restaurant Fixtures","American Food","Wholsale Restaurant Supplies","Veg Restaurants","Barbecue Restaurants","Non-Veg Restaurants"]
var displayDataArray:[String] = []
let searchString:NSString = (textField.text!).lowercased() as NSString
for string in self.dummyStringsArray {
let mainString:NSString = string.lowercased() as NSString
if mainString.length >= searchString.length {
let compareString = String(mainString.substring(to: searchString.length))
if searchString as String == compareString {
displayDataArray.append(string)
}
}
}
}
因此,如果我在textField中输入文字为&#39; 重新&#39;那么它应该返回包含&#34;餐厅&#34;,&#34;餐厅设备&#34;等值的displayDataArray。
答案 0 :(得分:0)
我认为你不能在没有任何循环的情况下这样做,因为你需要经历所有的元素
但我可以使用$days=$model->days; // comma saperated days
$days=explode(',',$days); // converting days into array
$count=0;
$start_date = $model->activity_start_date; // i.e. 2018-03-27
$end_date = date('Y-m-d');
while(strtotime($start_date) <= strtotime($end_date)){
if(in_array(date("N",strtotime($start_date)),$days)){ // check for day no
$count++;
}
$start_date = date ("Y-m-d", strtotime("+1 day", strtotime($start_date)));
}
函数为您提供更优雅的解决方案:
filter
答案 1 :(得分:0)
在传递range(of:options:)
和.caseInsensitive
的选项时,使用.anchored
可能会获得最佳效果。
func search() -> Void {
let dummyStringsArray = ["Hotel Restaurants","Restaurants","Certified Green Restaurant(R)","Japnies Food Restauarants","Grill Restaurants","Restaurant Equipment","Wholsale Restaurant Fixtures","American Food","Wholsale Restaurant Supplies","Veg Restaurants","Barbecue Restaurants","Non-Veg Restaurants"]
let searchString = textField.text!
let displayDataArray = dummyStringsArray.filter { $0.range(of: searchString, options: [ .caseInsensitive, .anchored ]) != nil }
}