4 ms·
Swift has the expressiblebyTypeliteral series of protocols for this. For example you could write an extension on Date to add initialization from a string:
by Aaargh20318 4y ago
Swift has the expressiblebyTypeliteral series of protocols for this.
For example you could write an extension on Date to add initialization from a string:
extension Date: ExpressibleByStringLiteral {
public init(stringLiteral value: String) {
// parse the string here.
}
}
You can then do things like:
let happyNewYear: Date = “2023-01-01 12:00:00”
There are a protocols for all literal types. For example, you could implement ExpressibleByIntegerLiteral and have have it init the Date object from a unix timestamp. There is even an ExpressibleByNilLiteral.
- culi 4y agoWell even JavaScript has custom string literal templates. Is this really that special?
- Too 4y agoC++ has the same with implicit constructors, generally considered to be a footgun that should be disabled with the explicit-keyword unless such a cast makes sense, implicit constructors are otherwise the default. For example vector has a constructor with takes integer size argument, if it wasn't explicit you could accidentally do vector v = {10} which would construct a vector with 10 empty elements, instead of one element with value 10. This also has to do with the ambigous curly brace syntax in c++.
- still_grokking 4y agoIt's "funny" that things that are considered an anti-feature and something that needs to be avoided by all means in one place is considered a great feature in another place. This points strongly in the direction that there is no logic behind such "considerations". What you just showed was a implicit conversion from String to Date. Something you would get beaten up for in Scala land.