Skip to content
DeveloperMemos

Converting URL to String and Back in Swift

Swift, URL, String Conversion1 min read

In Swift development, you may often need to convert URLs to strings and vice versa. This could be for storing URLs in a database, passing them around in your app, or other reasons. This article will guide you through the process of converting a URL to a String and then back to a URL in Swift.

Converting a URL to a String

To convert a URL object to a String, you can use the absoluteString property. This property returns the URL as a String, including the scheme (like http, file, etc.).

Example:

1let url = URL(string: "https://www.example.com")!
2let urlString = url.absoluteString
3print(urlString) // Outputs: "https://www.example.com"

Converting a String to a URL

When converting a string to a URL, you can use the URL(string:) initializer. This initializer returns an optional URL, which will be nil if the string is not a valid URL.

Example:

1let urlString = "https://www.example.com"
2if let url = URL(string: urlString) {
3 print(url) // Outputs: URL object
4} else {
5 print("Invalid URL")
6}

Handling File URLs

For file URLs, you can use the URL(fileURLWithPath:) initializer. This is particularly useful for local file paths.

Example:

1let filePath = "/path/to/file.txt"
2let fileURL = URL(fileURLWithPath: filePath)
3print(fileURL) // Outputs: file:///path/to/file.txt

To convert a file URL back to a string representing the file path, use the path property:

1let urlString = fileURL.path
2print(urlString) // Outputs: "/path/to/file.txt"