parse a url in swift

To parse a URL in Swift, you can use the URLComponents API from the Foundation framework. Here's an example:

main.swift
let urlString = "https://www.example.com/path/to/resource?key1=value1&key2=value2"
if let url = URL(string: urlString) {
    if let scheme = url.scheme,
        let host = url.host,
        let path = url.path,
        let queryItems = URLComponents(string: urlString)?.queryItems {
            
        print("Scheme: \(scheme)")
        print("Host: \(host)")
        print("Path: \(path)")
        
        for item in queryItems {
            print("\(item.name) = \(item.value ?? "")")
        }
    }
}
509 chars
17 lines

In this example, we first create a string that represents a URL. Then we create an instance of URL from this string. We then use optional binding to extract the individual components of the URL such as the scheme, host, path, and query items.

Note that the query items are obtained by using the URLComponents API, which is a more effective way of dealing with the URL query parameters than manually parsing the query string.

Output:

main.swift
Scheme: https
Host: www.example.com
Path: /path/to/resource
key1 = value1
key2 = value2
88 chars
6 lines

gistlibby LogSnag