Movatterモバイル変換


[0]ホーム

URL:


Friday,July28,2017

A Binary Coder for Swift

Mike Ash:

This coder serializes fields by writing them out sequentially as raw bytes, with no metadata.

[…]

Now we can see why I implementedBinaryEncoder’sencode method with a bigswitch statement instead of using separate implementations for all of the various supported types. Overloaded methods are resolved at compile time based on the static type that’s available at the call site. The above call toencoder.encode(value) will always callfunc encode(_ encodable: Encodable) even if the actual value passed in is, say, aDouble or aBool. In order to allow for this simple wrapper, the implementation inBinaryEncoder has to work with a single entry point, which means it needs to be a bigswitch statement.

[…]

Swift’s newCodable protocols are a welcome addition to the language to eliminate a lot of boilerplate code. It’s flexible enough to make it straightforward to use/abuse it for things well beyond JSON and property list parsing. Unsophisticated binary formats such as this are not often called for, but they have their uses, and it’s interesting to see howCodable can be used for something so different from the built-in facilities. TheEncoder andDecoder protocols are large, but judicious use of generics can cut down a lot of the repetitive code, and implementation is relatively simple in the end.

See also:HashingSingleValueEncodingContainer,MinimalDecoder (viaStephen Celis).

Previously:Swift.Codable.

Update (2017-07-31): See also:Hacker News.

CommentsRSS ·Twitter

Leave a Comment

  

Black Friday
Blog
Archives
Tag Cloud
Top Posts

Recently Updated
RSS Feed ·Comments
Mastodon ·Twitter
Apple News
Trackback

Support this site viaPatreon.

Try my Mac apps:

DropDMGDropDMGDropDMG
EagleFilerEagleFilerEagleFiler
SpamSieveSpamSieveSpamSieve
ToothFairyToothFairyToothFairy
Copyright © 2000–2025Michael Tsai.

[8]ページ先頭

©2009-2025 Movatter.jp