问题
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