young
(rtSwift)
1
Using the newly introduced FormatStyle, for output it's nice and simple:
Date().formatted(.iso8601) // shorthand notation works b/c inference works
Now I need this FormatStyle for parsing:
aDate = try Date.ISO8601FormatStyle.iso8601.parse(someString)
But is there anyway to skip the full qualification, like:
aDate = try .iso8601.parse(someString) // doesn't compile
// this is assigning to a Date, why can't it infer like the output side?
???
Edit: this makes it work the way I want:
func parse<PS: ParseStrategy>(_ input: PS.ParseInput, with strategy: PS) throws -> PS.ParseOutput {
try strategy.parse(input)
}
...
aDate = try parse(someString, with: .iso8601)
This parse() function make using these new FormatStyle that's ParsableFormatStyle simpler and easier with autocomplete. Is there no such thing exist already in Foundation? How to go about looking/searching for this if it exist?
Edit: the answer is no need for something like the parse(...) function. Foundation added new init's to parse input to that value with ParseStrategy. For Date:
try Date(rawValue, strategy: .iso8601)
Same kind of init's exist on BinaryInteger, BinaryFloatingPoint.
1 Like
Jon_Shier
(Jon Shier)
2
If you really want a chainable parsing function, you could add it to String.
extension String {
func parsingDate(usingStrategy strategy: ParseStrategy) throws -> Date {
try Date(self, strategy: strategy)
}
}
1 Like