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:

Image of Docusign

Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay