Swiftpack.co - Package - pinterest/plank

Plank logo


Build status

Plank is a command-line tool for generating robust immutable Objective-C models from JSON Schemas. It will save you time writing boilerplate and eliminate model errors as your application scales in complexity.


Models are defined in JSON, a well-defined, extensible and language-independent specification.

Immutable Classes

Model classes are generated to be immutable. Each class provides a “Builder” class to handle mutation.

Type safe

Based on the type information specified in the schema definition, each class provides type validation and null reference checks to ensure model integrity.



$ brew install pinterest/tap/plank


Plank supports building in Ubuntu Linux via Docker. The Dockerfile in the repository will fetch the most recent release of plank and build dependencies including the Swift snapshot.

$ docker build -t plank .

Build from source

Plank is built using the Swift Package Manager. Although you’ll be able to build Plank using swift build directly, for distribution of the binary we’d recommend using the commands in the Makefile since they will pass the necessary flags to bundle the Swift runtime.

$ make archive

Getting Started

Keep reading to learn about Plank’s features or get your feet wet with the tutorial.

Defining a schema

Plank takes a schema file as an input. Schemas are based on JSON, a well-defined, extensible and language-independent specification. Defining schemas in JSON allowed us to avoid writing unnecessary parser code and opened up the possibility of generating code from the same type system used on the server.

    "id": "pin.json",
    "title": "pin",
    "description" : "Schema definition of a Pin",
    "$schema": "http://json-schema.org/schema#",
    "type": "object",
    "properties": {
        "id": { "type": "string" },
        "link": { "type": "string", "format": "uri"}

You’ll notice we specify the name of the model and a list of its properties. Note that link specifies an additional format attribute which tells Plank to use a more concrete type like NSURL or NSDate.

Generating a model

Generate a schema file (pin.json) using Plank using the format plank [options] file1 file2 file3 ...

$ plank pin.json

This will generate files (Pin.h, Pin.m) in the current directory:

$ ls
pin.json Pin.h Pin.m

Learn more about usage on the installation page.

Generated Output

Plank will generate the necessary header and implementation file for your schema definition. Here is the output of the Pin.h header.

@interface Pin
@property (nonatomic, copy, readonly) NSString *identifier;
@property (nonatomic, strong, readonly) NSURL *link;

All properties are readonly, as this makes the class immutable. Populating instances of your model with values is performed by builder classes.

Mutations through builders

Model mutations are performed through a builder class. The builder class is a separate type which contains readwrite properties and a build method that will create a new object. Here is the header of the builder that Plank generated for the Pin model:

@interface PinBuilder
@property (nonatomic, copy, readwrite) NSString *identifier;
@property (nonatomic, strong, readwrite) NSURL *link;
- (Pin *)build;

@interface Pin (BuilderAdditions)
- (instancetype)initWithBuilder:(PinBuilder *)builder;

JSON parsing

Plank will create an initializer method called initWithModelDictionary: that handles parsing NSDictionary objects that conform to your schema. The generated implementation will perform validation checks based on the schema’s types, avoiding the dreaded [NSNull null] showing up in your objects:

@interface Pin (JSON)
- (instancetype)initWithModelDictionary:(NSDictionary *)dictionary;


All Plank generated models implement methods to conform to NSSecureCoding, providing native serialization support out of the box.

+ (BOOL)supportsSecureCoding {
    return YES;

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    if (!(self = [super init])) { return self; }
    _identifier = [aDecoder decodeObjectOfClass:[NSString class] forKey:@"identifier"];
    _link = [aDecoder decodeObjectOfClass:[NSURL class] forKey:@"link"];
    return self;

- (void)encodeWithCoder:(NSCoder *)aCoder {
    [aCoder encodeObject:self.identifier forKey:@"identifier"];
    [aCoder encodeObject:self.link forKey:@"link"];

With this implementation objects are serialized using NSKeyedArchiver:

// Create a pin from a server response
Pin *pin = [[Pin alloc] initWithModelDictionary:/* server response */];
// Cache the pin
[NSKeyedArchiver archiveRootObject:pin toFile:/* cached pin path */];
// App goes on, terminates, restarts...
// Load the cached object
Pin *cachedPin = [NSKeyedUnarchiver unarchiveObjectWithFile:/* cached pin path */];

Model merging and partial data

Plank models support merging and partial object materialization through a conventional “last writer wins” approach. By calling the mergeWithModel: on a generated model with a newer instance, the properties set on the newer instance will be preserved. To know which properties are set, the information is tracked internally within the model during initialization or through any mutation methods. In this example, an identifier property is used as a primary key for object equality:

static inline id valueOrNil(NSDictionary *dict, NSString *key);
struct PinSetProperties {
  unsigned int Identifier:1;
  unsigned int Link:1;
- (instancetype)initWithModelDictionary:(NSDictionary *)modelDictionary {
  [modelDictionary enumerateKeysAndObjectsUsingBlock:^(NSString *  _Nonnull key, id obj, BOOL *stop){
    if ([key isEqualToString:@"identifier"]) {
        // ... Set self.identifier
        self->_pinSetProperties.Identifier = 1;
    if ([key isEqualToString:@"link"]) {
        // ... Set self.link
        self->_pinSetProperties.Link = 1;
  // Post notification
  [[NSNotificationCenter defaultCenter] postNotificationName:@"kPlankModelDidInitializeNotification" object:self];

With immutable models, you have to think through how data flows through your application and how to keep a consistent state. At the end of every model class initializer, there’s a notification posted with the updated model. This is useful for integrating with your data consistency framework. With this you can track whenever a model has updated and can use internal tracking to merge the new model.

@implementation Pin(ModelMerge)
- (instancetype)mergeWithModel:(Pin *)modelObject {
    PinBuilder *builder = [[PinBuilder alloc] initWithModelObject:self];
    if (modelObject.pinSetProperties.Identifier) {
        builder.identifier = modelObject.identifier;
    if (modelObject.pinSetProperties.Link) {
        builder.link = modelObject.link;
    return [builder build];

Algebraic data types

Plank provides support for specifying multiple model types in a single property, commonly referred to as an Algebraic Data Type (ADT). In this example, the Pin schema receives an attribution property that will be either a User, Board, or Interest. Assume we have separate schemas defined in files user.json, board.json and interest.json, respectively.

    "title": "pin",
    "properties": {
        "identifier": { "type": "string" },
        "link": { "type": "string", "format": "uri"},
        "attribution": {
          "oneOf": [
            { "$ref": "user.json" },
            { "$ref": "board.json" },
            { "$ref": "interest.json" }

Plank takes this definition of attribution and creates the necessary boilerplate code to handle each possibility. It also provides additional type-safety by generating a new class to represent your ADT.

@interface PinAttribution : NSObject<NSCopying, NSSecureCoding>
+ (instancetype)objectWithUser:(User *)user;
+ (instancetype)objectWithBoard:(Board *)board;
+ (instancetype)objectWithInterest:(Interest *)interest;
- (void)matchUser:(void (^)(User * pin))userMatchHandler
          orBoard:(void (^)(Board * board))boardMatchHandler
       orInterest:(void (^)(Interest * interest))interestMatchHandler;

Note there’s a “match” function declared in the header. This is how you extract the true underlying value of your ADT instance. This approach guarantees at compile-time you have explicitly handled every possible case preventing bugs and reducing the needs to use runtime reflection which hinders performance. The example below shows how you’d use this match function.

PinAttribution *attribution;
[attribution matchUser:^(User *user) {
   // Do something with "user"
} orBoard:^(Board *board) {
   // Do something with "board"
} orInterest:^(Interest *interest) {
   // Do something with "interest"


Pull requests for bug fixes and features welcomed.


Copyright 2017 Pinterest, Inc.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.


Stars: 368
Help us keep the lights on


Used By

Total: 0


v1.2.1 - Jan 17, 2018


  • Added make install to Makefile. Use PREFIX to specify a different installation path than /usr/local

Basic Usage:

make install

Usage with custom installation path:

make install PREFIX=/usr/local/Cellar/plank/1.2.1
  • Address issues identified by SwiftLint
  • Add documentation for Set type


56012d6 Add make install target to Makefile (#109) 4c3f228 Add autocorrect step to Swiftlint (#107) 3bdc34f Add Set to docs on property fields (#105)

v1.2 - Dec 15, 2017

In this release:

  • Support NSSet for Objective-C, Flow
  • Updates to nullability, equality and memory assignment for ObjC
  • Fix archiving to disable sandboxing and homebrew installation
  • Update documentation

Commits -

801d97e Use copy for NSURL and NSDate 4bdf16d Build archives with sandboxing disabled to allow homebrew installations (#102) 386c378 Update the .PHONY target list (#98) 5612063 Address lint warnings under swiftlint 0.24.0 (#99) 6bd7921 Don't generate dictionary representation until we can verify it compiles (#96) b870223 Correct integer example (#95) 91d26a0 Rename dictionaryRepresentation method so it doesn't conflict with Foundation's one (#94) 56a6d99 Removes usage of deprecated characters from String (#93) d480449 Added support for NSSet properties (#91) 4de2627 Update ObjC builder extension to be aware of nullability of properties (#88) 8d84d74 Remove default case that will never be executed (#87) ad1aed3 Fix issue with generating the dictionaryRepresentation method for schemas that (#85) c5ed50a Expand list of reserved objc keywords to cover most conflicting case (#79) 3fc1bea Fix make clean command(#65) 6399daf ObjectiveCDictionaryExtension to correctly handle maps of root objects (#81) 9bc92b3 Compare NSArrays using -isEqualToArray: (#83) c855031 Update indentation settings in plank.xcodeproj (#82) f8378f6 Objective-C init extension to better handle null model dictionary in prod builds (#80) 92c9a3f Bazel build support for Plank (#75)

v1.1 - Aug 17, 2017

Version 1.1

New CLI options

    --print_deps - Just print the path to the dependent schemas necessary to generate the schemas provided and exit.
    --no_recursive - Don't generate files recursively. Only generate the one file I ask for.
    --only_runtime - Only generate runtime files and exit.
    --lang - Comma separated list of target language(s) for generating code. Default: "objc"
    --help - Show this text and exit.

Flow Support

This release contains an early experimental implementation of Flow type generation. Now your schema files can be used to generate multiple languages by using the --lang command line option.

How do I use it?

  • Try it out by specifying --lang flow
  • Generate both ObjC and Flow --lang flow,objc

More documentation on Flow is coming soon but you can see the current output in the Examples.

Objective-C Generation

  • Nullability: Specifying a field as required will now influence if it is nonnull or nullable. Previously all methods were nullable.
  • New Method: "- (NSDictionary *)dictionaryRepresentation" allows your models to output a dictionary representation of themselves. This is intended to be the inverse of initWithModelDictionary.
  • Bug fixes: Small number of fixes to the generated code have been made.

Notable commits in this release:

864abac Nullability support in Plank: (#64) 6808341 Add dictionary representation to Objc models (#67) fc967d5 Add tests for generated models to the integration tests pipeline (#69) 116b818 Copy the value to an ivar backed by a copy property (#72) 0d50564 Add custom indentation support (#61) 37a6bc3 Don't camel case the description for EnumValue by default (#60) 12db0da Add Flow Type Support (#57) 6d226ec Fix lint warnings (#58) 332af42 Use relative schema urls internally (#59) 46d340f Fix critical bug where deep equality comparison contained a pointer equality (#50) 658c73f Add initial support for integration testing. (#48) aba7ecc Remove FilePrinter protocol (#46) 86873d0 Update to newest CI (#44) 69e6d20 Add lang attribute to provide future flexibility for additional languages in (#42) d69c8e6 Simplify initWithModelDictionary and improve performance (#40) e8d35e3 Update Plank to Swift 3.1 (#39) 38f6da3 Makes the code more readable via early returns / fatal errors in guards (#35) 9fefe3a Support for no_recursive and only_runtime flags. Fix print_deps output (#32) 120e4d2 Add cli option for printing the dependencies of a schema (#30)

v1.0 - Mar 14, 2017

This is the initial public release of plank.