Piggyback on URLComponents
:
var components = URLComponents()
components.query = "id=sfghsgh=sbfsfhj&name=awsjdk_fs"
components.queryItems
// => Optional([id=sfghsgh=sbfsfhj, name=awsjdk_fs])
let list = components.queryItems?.map { ($0.name, $0.value) } ?? []
// [("id", Optional("sfghsgh=sbfsfhj")), ("name", Optional("awsjdk_fs"))]
let dict = Dictionary(list, uniquingKeysWith: { a, b in b })
// ["name": Optional("awsjdk_fs"), "id": Optional("sfghsgh=sbfsfhj")]
Если вам нужно [String: String]
вместо [String: String?]
:
let list = components.queryItems?.compactMap { ($0.name, $0.value) as? (String, String) } ?? []
// [("id", "sfghsgh=sbfsfhj"), ("name", "awsjdk_fs")]
let dict = Dictionary(list, uniquingKeysWith: { a, b in b })
// ["name": "awsjdk_fs", "id": "sfghsgh=sbfsfhj"]