user2636197 user2636197 - 1 month ago 6
Swift Question

Swift concatenate string based on different values

I need to concatenate a string based on some logic but I cant figure out how to do it.

Example:

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
}


This will only work if I have ONE filter in my query

Eg:
query.filters = "location_id=4"


But if I happend to have two or more filters my query will break eg:

query.filters = "location_id=4cat_id=3"


If I have more then one filter I need to seperate it with a AND statement like this:

query.filters = "location_id=4 AND cat_id=3"


But I cant figure out how to do it since I never know what order the filter will come in or if there even will be one or more filters to begin with

Edit

I seem to get it working by:

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
}

Answer

Another option using inline if statements:

    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
    }
Comments