我需要根据某些逻辑连接一个字符串,但我无法弄清楚如何去做。
示例:
var filterString: String = ""
var hasFilter: Bool = false
if let catId = param["catid"] {
filterString += "cat_id=\(catId)"
hasFilter = true
}
if let subCatId = param["subcatid"] {
filterString += "sub_cat_id=\(subCatId)"
hasFilter = true
}
if let locationId = param["stateid"] {
filterString += "location_id=\(locationId)"
hasFilter = true
}
if hasFilter == true {
query.filters = filterString
}
只有在我的查询中 ONE 过滤器
时才会有效例如:query.filters = "location_id=4"
但如果我发生了两个或更多过滤器,我的查询就会破坏,例如:
query.filters = "location_id=4cat_id=3"
如果我有一个以上的过滤器,我需要用这样的AND语句分隔它:
query.filters = "location_id=4 AND cat_id=3"
但我无法弄清楚如何做到这一点,因为我从来不知道过滤器的顺序是什么,或者是否会有一个或多个过滤器开始
修改
我似乎通过以下方式开展工作:
var filterString: String = ""
var hasFilter: Bool = false
if let catId = param["catid"] {
filterString += "cat_id=\(catId)"
hasFilter = true
}
if let subCatId = param["subcatid"] {
if hasFilter == true {
filterString += " AND sub_cat_id=\(subCatId)"
} else {
filterString += "sub_cat_id=\(subCatId)"
}
hasFilter = true
}
if let locationId = param["stateid"] {
if hasFilter == true {
filterString += " AND location_id=\(locationId)"
} else {
filterString += "location_id=\(locationId)"
}
hasFilter = true
}
if hasFilter == true {
query.filters = filterString
}
答案 0 :(得分:2)
一种解决方案是将过滤器放入数组中,然后如果数组不为空,则将数组值与" AND "
分隔符合并。
var filters : [String] = []
if let catId = param["catid"] {
filters.append("cat_id=\(catId)")
}
if let subCatId = param["subcatid"] {
filters.append("sub_cat_id=\(subCatId)")
}
if let locationId = param["stateid"] {
filters.append("location_id=\(locationId)")
}
if filters.count > 0 {
query.filters = filters.joined(separator: " AND ")
}
答案 1 :(得分:0)
也许您可以先创建一个数组并附加所有过滤器。 之后创建另一个变量以附加数组中的所有值。
答案 2 :(得分:0)
使用内联if语句的另一个选项:
var param = ["catid" : "111", "subcatid" : "222", "stateid" : "333"]
var filterString = ""
if let catId = param["catid"] {
filterString = "cat_id=\(catId)"
}
if let subCatId = param["subcatid"] {
filterString.appendContentsOf(filterString.characters.count > 0 ? " AND sub_cat_id=\(subCatId)" : "sub_cat_id=\(subCatId)")
}
if let locationId = param["stateid"] {
filterString.appendContentsOf(filterString.characters.count > 0 ? " AND location_id=\(locationId)" : "location_id=\(locationId)")
}
print(filterString)
if (filterString.characters.count > 0) {
query.filters = filterString
}