Thursday, June 16, 2022

ParsableFormatStyle

Brett Ohland:

Apple’s modern Swift replacement system for Formatter is a set of protocols: FormatStyle and ParseableFormatStyle. The former handles the conversion to strings, and the latter strings to data.

[…]

The most direct way of parsing a string into it’s respective data type is to create an instance of a ParseableFormatStyle that’s set up to understand the structure of the incoming string. From there you access it’s parseStrategy property, and call the parse() method on it.

This is a bit cumbersome, so Apple has included custom initializers onto each of the supported data types that take the string and either a ParseableFormatStyle or a ParseStrategy instance to do the parsing. What’s interesting is that Apple includes initializers that can accept any input type, as long as you provide a ParseStrategy that informs the type how to parse it. Aren’t constrained generics neat?

[…]

New for iOS 16, you can now parse URLs using this exact manner[…]

Previously:

Comments RSS · Twitter

Leave a Comment