Url Parsing in Swift
Here’s the translation of the URL parsing example from Go to Swift:
import Foundation
func main() {
// We'll parse this example URL, which includes a
// scheme, authentication info, host, port, path,
// query params, and query fragment.
let s = "postgres://user:pass@host.com:5432/path?k=v#f"
// Parse the URL and ensure there are no errors.
guard let u = URL(string: s) else {
fatalError("Invalid URL")
}
// Accessing the scheme is straightforward.
print(u.scheme ?? "")
// User contains all authentication info; we can access
// username and password separately.
if let components = URLComponents(url: u, resolvingAgainstBaseURL: false),
let user = components.user,
let password = components.password {
print("\(user):\(password)")
print(user)
print(password)
}
// The host contains both the hostname and the port,
// if present. We can extract them separately.
print(u.host ?? "")
print(u.port ?? 0)
// Here we extract the path and the fragment after the #.
print(u.path)
print(u.fragment ?? "")
// To get query params in a string of k=v format,
// use query. You can also parse query params
// into a dictionary.
if let components = URLComponents(url: u, resolvingAgainstBaseURL: false) {
print(components.query ?? "")
if let queryItems = components.queryItems {
let queryDict = Dictionary(uniqueKeysWithValues: queryItems.map { ($0.name, $0.value ?? "") })
print(queryDict)
print(queryDict["k"] ?? "")
}
}
}
main()
This Swift code demonstrates URL parsing using the Foundation
framework. Here’s a breakdown of the changes and explanations:
We use
URL
andURLComponents
classes from theFoundation
framework to parse and manipulate URLs.Instead of
url.Parse()
, we useURL(string:)
to create a URL object.Swift’s optional binding (
if let
) and guard statements are used for error handling and safe unwrapping of optional values.The
User
information is accessed throughURLComponents
as Swift’sURL
doesn’t provide direct access to user and password.Host and port are accessed separately in Swift using
u.host
andu.port
.Query parameters are parsed using
URLComponents.queryItems
, which returns an array ofURLQueryItem
objects. We convert this to a dictionary for easier access.Swift doesn’t have a direct equivalent to Go’s
net.SplitHostPort()
, so we access host and port separately.
Running this Swift program would output similar results to the Go version, showing all the different pieces extracted from the URL.
Note that Swift’s URL parsing capabilities are slightly different from Go’s, but this example covers most of the same functionality.