Reputation: 1979
I'd like to make the following an extension of NSURL instead of a function but I'm getting errors that I can't use the variables. How would I fix this?
The function gets the query string of a url and returns a dictionary with key value pairs of the parameters in the query.
func getKeyVals(url:NSURL) -> Dictionary<String, String>{
var results = [String:String]()
var keyValues = url.query?.componentsSeparatedByString("&")
if keyValues?.count > 0 {
for pair in keyValues! {
let kv = pair.componentsSeparatedByString("=")
if kv.count > 1 {
results.updateValue(kv[1], forKey: kv[0])
}
}
}
return results
}
Upvotes: 0
Views: 48
Reputation: 236420
extension NSURL {
func getKeyVals() -> Dictionary<String, String> {
var results = [String:String]()
let keyValues = query?.componentsSeparatedByString("&")
if keyValues?.count > 0 {
for pair in keyValues! {
let kv = pair.componentsSeparatedByString("=")
if kv.count > 1 {
results.updateValue(kv[1], forKey: kv[0])
}
}
}
return results
}
}
if let checkedUrl = NSURL(string: "http://www.domain.com/index.php?device=iPad&capacity=128GB&color=white"){
let keyVals = checkedUrl.getKeyVals() // ["color": "white", "device": "iPad", "capacity": "128GB"]
}
Upvotes: 2