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
}
}
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
- Understanding Package.swift • 13 minutes reading time.
- @Environment variables • 4 minutes reading time.
- Inspect: A Powerful Tool for SwiftUI Developers • 3 minutes reading time.
Share
Share Mastodon Twitter LinkedIn Facebook