[Solved] Any shorthand way to get the static var .iso8601 from Date.ISO8601FormatStyle for parsing string into a Date?

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

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
Terms of Service

Privacy Policy

Cookie Policy