— Swift, URL, String Conversion — 1 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.
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.absoluteString3print(urlString) // Outputs: "https://www.example.com"
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 object4} else {5 print("Invalid URL")6}
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.path2print(urlString) // Outputs: "/path/to/file.txt"