swift 3 get a substring from query params

半腔热情 提交于 2019-12-13 02:12:50

问题


I want to get a substring from a larger string in swift 3. The string is just the query part of a url:

user_one_id=7&user_two_id=5

I just want the id of each user, so I want 7 and 5.


回答1:


A quite simple solution is to create URLComponents, assign the query part and (flat)map the query items to their values

let string = "user_one_id=7&user_two_id=5" let components = URLComponents(string: "http://dummy.com?" + string) let userIDs = components?.queryItems?.flatMap{ $0.value } print(userIDs)

let string = "user_one_id=7&user_two_id=5"
var components = URLComponents()
components.query = string
let userIDs = components.queryItems!.flatMap{ $0.value }
print(userIDs)


来源:https://stackoverflow.com/questions/46160472/swift-3-get-a-substring-from-query-params

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!