Wesley de Groot's Blog
ExpressibleByStringLiteral URL

Back

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
    }
}

Use Case: ExpressibleByStringLiteral for URLs

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

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:

Read more

Share


Share Mastodon Twitter LinkedIn Facebook
x-twitter mastodon github linkedin discord threads instagram whatsapp bluesky square-rss sitemap