I need to append some query parameters to my API URL. The consumer of my API would pass me this optional structure called as APIParameters, which contain 5 optionals, one array of strings and rest strings
Lets assume the following:
let baseURL = "baseURL"
let path = "path"
This is the final URL structure
//assuming since and offset is nil, this would be the URL
result = "baseURL" + "path" + "?"+ "with=some1,some2,some3&limit=100&width=0"
To solve this, I made a struct, and added a method to return me the string that I need to append to my URL.
struct APIParameters {
var with: [String]?
var since: NSDate?
var width: Int?
var offset: Int?
var limit: Int?
func stringToAppendToURL() -> String{
//started with this approach
var stringToAppend = ""
if with != nil {
var withParamaters = ",".join(with!)
println("withParamaters = \(withParamaters)")
stringToAppend += "with=\(withParamaters)"
}
if limit != nil {
println("limit = \(limit)")
}
//realized this would be too long so tried using switch
switch (with, limit, width, offset, since){
case (nil, nil, nil, nil, nil):
return ""
case (.Some(let withParameters), nil, nil, nil, nil):
return "with=" + ",".join(withParameters)
case (nil, .Some(let limitParams), nil, nil, nil):
return "limit=\(limitParams)"
case (nil, nil, .Some(let widthParams), nil, nil):
return "width=\(widthParams)"
case (nil, nil, nil, .Some(let offsetParams), nil):
return "offset=\(offsetParams)"
case (nil, nil, nil, nil, .Some(let sinceParams)):
return "since=\(Int(sinceParams.timeIntervalSince1970))"
case (.Some(let withParams), .Some(let limitParams), nil, nil, nil):
return "with=" + ",".join(withParams) + "&" + "limit=\(limitParams)"
//realized that number of conditions would become too many so decided to ask for help
default:
return ""
}
}
}
Example:
let apiParams1 = APIParameters(with: ["option", "full"], since: nil, width: nil, offset: nil, limit: 10) let apiParams2 = APIParameters(with: ["option", "full"], since: nil, width: nil, offset: nil, limit: nil) println("\(apiParams1.stringToAppendToURL())") println("\(apiParams2.stringToAppendToURL())")
Output:
"with=option,full&limit=10" "with=option,full"
Is there a more elegant way to do this?