It seems quite clear that Swift will get more powerful runtime reflection APIs in the future, probably post ABI-stabilization. But before that happens, I'd like to find out if Custom Attributes, a feature I love from C# and think would do wonders for Swift, could be added later, or if the current ABI doesn't have *space" for it.
Very quickly, such a feature would allow users to define their own attributes (with metadata) and attach them to types/members. Once we get reflection APIs, we could then query them at runtime. It has many uses. For example, C# uses them for their serialisation API. Swift could use them to provide an alternative method for customising Codable properties:
member attribute codable {
let key: String?
let dateFormatter: DateFormatter?
let dataFormatter: DataFormatter?
init(key: String? = nil) {
self.key = key
self.dateFormatter = nil
self.dataFormatter = nil
}
}
extension codable where Self == Date {
init(key: String? = nil, formatter: DateFormatter) {
self.init(key: key)
self.dateFormatter = formatter
}
}
extension codable where Self == Data {
init(key: String? = nil, formatter: DataFormatter) {
self.init(key: key)
self.dataFormatter = formatter
}
}
struct Person: Codable {
@codable(key: "first_name")
let firstName: String
@codable(key: "date_of_birth", formatter: .dayFormatter)
let dateOfBirth: Date
@codable(key: "finger_print", formatter: .secureFormatter)
let fingerPrint: Data
}
// With imaginative runtime APIs
let person: Person = ...
let personReflection = Reflection(person)
for property in personReflection.properties {
for attribute in property.attributes {
if let codable = attribute as? @codable {
// ...
}
}
}