Sco*_*ott 4 string parsing swift
我正在编写各种迷你控制台,我正试图弄清楚如何从链接中提取内容.例如,在PHP中,这是一个请求变量,因此:
http://somelink.com/somephp.php?variable1=10&variable2=20
然后PHP计算出url参数并将它们分配给变量.
我如何在Swift中解析这样的东西?
所以,给定我想要的字符串:variable1 = 10和variable2 = 20等,有一个简单的方法吗?我试着用Google搜索,但并不知道我在搜索什么.
我有一个非常可怕的hacky方式这样做,但它不是真的可扩展.
你想要的是NSURLComponents:
import Foundation
let urlStr = "http://somelink.com/somephp.php?variable1=10&variable2=20"
let components = NSURLComponents(string: urlStr)
components?.queryItems?.first?.name // Optional("variable1")
components?.queryItems?.first?.value // Optional("10")
Run Code Online (Sandbox Code Playgroud)
您可能会发现subscript为查询项添加运算符很有帮助:
extension NSURLComponents {
subscript(queryItemName: String) -> String? {
// of course, if you do this a lot,
// cache it in a dictionary instead
for item in self.queryItems ?? [] {
if item.name == queryItemName {
return item.value
}
}
return nil
}
}
if let components = NSURLComponents(string: urlStr) {
components["variable1"] ?? "No value"
}
Run Code Online (Sandbox Code Playgroud)