Written by Sean Behan on Sun Sep 23rd 2018

Here is an extension you can use in your Swift (v4) projects that makes it easy to parse parameters from a url.

Given a url like, "http://example.com/?x=1&y=2", you can extract the x and y parameters into a key, value data structure.

Here is the snippet...

extension URL {
  func params() -> [String:Any] {
    var dict = [String:Any]()

    if let components = URLComponents(url: self, resolvingAgainstBaseURL: false) {
      if let queryItems = components.queryItems {
        for item in queryItems {
          dict[item.name] = item.value!
        }
      }
      return dict
    } else {
      return [:]
    }
  }
}

And you can use it like this..

  URL(string:"http://example.com/?x=1&y=2").params()
  // ["x" : 1, "y": 2]

That's it!


Tagged with..
#swift #ios #xcode #macos #urls #parsing strings

Just finishing up brewing up some fresh ground comments...