Expressible Literals
Expressible Literals in Swift are a powerful feature that allows you to create custom types that can be initialized using literals.
This post will show you how to create your own custom types that can be initialized using literals.
What is a literal?
A literal is a notation for representing a fixed value such as integers, strings, and booleans.
Literals in Swift are made possible by several available protocols.
Standard types conform to these protocols and allow us to initialize values as follows:
var integer = 0 // ExpressibleByIntegerLiteral
var string = "Hello!" // ExpressibleByStringLiteral
var array = [0, 1, 2] // ExpressibleByArrayLiteral
var dictionary = ["Key": "Value"] // ExpressibleByDictionaryLiteral
var boolean = true // ExpressibleByBooleanLiteral
How to create a custom type that can be initialized using literals
// ExpressibleBy..Literal protocol is used to create custom types that can be initialized using literals
extension CLASS: ExpressibleByStringLiteral {
// Required initializer for ExpressibleBy...Literal
public init(stringLiteral value: String) {
// Initialize the class with the ... value
self.init(value)
}
}
Example 1: Image
Before:
import SwiftUI
let myImage = Image(named: "imageName")
Using ExpressibleByStringLiteral:
import SwiftUI
extension Image: ExpressibleByStringLiteral {
public init(stringLiteral value: String) {
self.init(value)
}
}
let myImage: Image = "imageName"
Example 2: URL
Before:
let myURL = URL(string: "https://wesleydegroot.nl")
Using ExpressibleByStringLiteral:
extension URL: ExpressibleByStringLiteral {
public init(stringLiteral value: String) {
self.init(string: value)!
}
}
let myURL: URL = "https://wesleydegroot.nl"
Example 3: Date
Before:
let formatter = DateFormatter()
formatter.dateFormat = "dd-MM-yyyy"
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.timeZone = TimeZone(secondsFromGMT: 0)
let date = formatter.date(from: "03-08-1990")
print(date) // Prints: 1990-08-03 00:00:00 +0000
Using ExpressibleByStringLiteral:
extension Date: ExpressibleByStringLiteral {
public init(stringLiteral value: String) {
let formatter = DateFormatter()
formatter.dateFormat = "dd-MM-yyyy"
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.timeZone = TimeZone(secondsFromGMT: 0)
self = formatter.date(from: value)!
}
}
let date: Date = "03-08-1990"
print(date) // Prints: 1990-08-03 00:00:00 +0000
Conclusion
Expressible Literals in Swift are a powerful feature that allows you to create custom types that can be initialized using literals.
Resources:
- https://developer.apple.com/documentation/swift/expressiblebystringliteral
- https://docs.swift.org/swift-book/documentation/the-swift-programming-language/initialization/
Read more
- Enhancing SwiftUI with CachedAsyncImage • 3 minutes reading time.
- Translating closures to async • 4 minutes reading time.
- TipKit • 3 minutes reading time.
Share
Share Bluesky Mastodon Twitter LinkedIn Facebook