因此,我试图在比赛后对所有内容进行子字符串化,但是出于某种原因,我只能得到一个字符。
let url = "http://localhost:3000/something/?page=2&per_page=20"
if let pageNumber = url.range(of: "per_page=", options: .backwards) {
// this prints "0" ? was kinda hoping for "20"
print(url.substring(from: pageNumber.upperBound))
}
编辑:好的,我将字符串更改为per_page,不带“ =”,现在可以使用了。不知道为什么。
.. url.range(of: "per_page", ..
答案 0 :(得分:1)
在Swift 4中,此代码应该可以工作
let url = "http://localhost:3000/something/?page=2&per_page=20"
if let pageNumber = url.range(of: "per_page=", options: .backwards) {
print(url[pageNumber.upperBound...])
}
但是,如果字符串表示URL,我建议使用URLComponents
API。
URLComponents
实例QueryItems
key
获取value
let url = "http://localhost:3000/something/?page=2&per_page=20"
if let urlComponents = URLComponents(string: url),
let queryItems = urlComponents.queryItems,
let perPage = queryItems.first(where: {$0.name == "per_page"}) {
print(perPage.value!)
}