DEV Community

Wesley de Groot
Wesley de Groot

Posted on • Originally published at wesleydegroot.nl on

ExpressibleByStringLiteral URL

The ExpressibleByStringLiteral protocol is a powerful feature in Swift that allows us to create custom types directly from string literals. Essentially, it enables us to initialize instances of our custom types using string values. This can be incredibly useful for scenarios where we want to represent certain data types more intuitively or avoid force unwrapping when dealing with known valid strings.

Writing the extension ExpressibleByStringLiteral

/// Lets URLs be expressed conveniently with literal strings:
/// # Example:
/// let baseUrl: URL = "https://wesleydegroot.nl/blog"
extension URL: ExpressibleByStringLiteral {
    public init(stringLiteral string: StaticString) {
        guard let url = URL(string: "\(string)") else {
            preconditionFailure("Invalid literal URL string: \(string)")
        }
        self = url
    }
}
Enter fullscreen mode Exit fullscreen mode

Use Case: ExpressibleByStringLiteral for URLs

let baseUrl: URL = "https://wesleydegroot.nl/blog"
print(baseUrl.absoluteString) // Output: "https://wesleydegroot.nl/blog"
Enter fullscreen mode Exit fullscreen mode

Conclusion

In summary, ExpressibleByStringLiteral empowers us to make our custom types more expressive and convenient to work with. By conforming to this protocol, we can simplify our code and enhance readability.

Remember to explore other use cases and experiment with different types to harness the full potential of ExpressibleByStringLiteral in your Swift projects!

Resources:

Top comments (0)