parse a url without foundation in swift

To parse a URL without using Foundation in Swift, you can use Regular Expressions. Regular Expression is a powerful tool for parsing strings and it can be used to extract specific parts of the URL.

Here is an example of a function that uses a Regular Expression to extract the host, path and query parameters from a URL string:

main.swift
func parseUrl(_ urlString: String) -> (String, String, [String: String])? {
    let pattern = #"^(?:([a-z][a-z0-9+\-.]*):\/\/)?([a-z0-9\-._~%!$&'()*+,;=]+)(\/[a-z0-9\-._~%!$&'()*+,;=]*)?(\?[a-z0-9\-._~%!$&'()*+,;=]+=[a-z0-9\-._~%!$&'()*+,;=]*)*$"#
    let regex = try! NSRegularExpression(pattern: pattern, options: [])
    guard let match = regex.firstMatch(in: urlString, options: [], range: NSRange(location: 0, length: urlString.utf16.count)) else {
        return nil
    }
    let hostRange = match.range(at: 2)
    let pathRange = match.range(at: 3)
    var queryParameters: [String: String] = [:]
    if match.numberOfRanges > 4 {
        let queryRange = match.range(at: 4)
        let query = (urlString as NSString).substring(with: queryRange)
        query.components(separatedBy: "&").forEach { param in
            let parts = param.components(separatedBy: "=")
            if parts.count == 2 {
                let key = parts[0].removingPercentEncoding ?? parts[0]
                let value = parts[1].removingPercentEncoding ?? parts[1]
                queryParameters[key] = value
            }
        }
    }
    let host = (urlString as NSString).substring(with: hostRange)
    let path = (urlString as NSString).substring(with: pathRange)
    return (host, path, queryParameters)
}
1304 chars
26 lines

This function takes a URL string as an argument and returns a tuple with the host, path and query parameters. You can call it like this:

main.swift
if let result = parseUrl("https://www.apple.com/search?q=iphone") {
    print("Host: \(result.0)")
    print("Path: \(result.1)")
    print("Query parameters: \(result.2)")
}
175 chars
6 lines

Output:

main.swift
Host: www.apple.com
Path: /search
Query parameters: ["q": "iphone"]
68 chars
4 lines

related categories

gistlibby LogSnag