Swift guarded model initializers for SwiftyJSON

Overview

Build Status

GuardedSwiftyJSON

Why should I use this?

This library makes initializing models with JSON data with SwiftyJSON a lot easier.

Often with SwiftyJSON I end up doing something like this:

import SwiftyJSON

struct Model {
  let name : String
  let height : Double

  init?(json: JSON) {
    guard let name = json["name"].string, let height = json["height"].double else {
      return nil
    }

    self.name = name
    self.height = height
  }
}

which gets annoying when you have more than two or three properties you want to guard your model on.

Example

GuardedSwiftyJSON solves this by providing an initializer which will fail the initialization if properties that you request are not present.

import GuardedSwiftyJSON

struct Model : JsonInitializable {
  let name : String
  let height : Double

  init(json: GuardedJSON) {
    name = json["name"].string
    height = json["height"].double
  }
}

And then your object will get an initializer that allows it to be created from a Swifty JSON object:

let data : JSON = ["name": "Arthur Swiftington", "height": 182.8]

let model : Model? = Model(json: data)

If either one of name or height are not present, the initialization will fail.

You can specify optional properties by using the optional prefix:

import GuardedSwiftyJSON

struct Model : JsonInitializable {
  let name : String
  let height : Double?

  init(json: GuardedJSON) {
    name = json["name"].string
    height = json["height"].optionalDouble
  }
}

Then, if those optional properties do not exist, they will not cause initialization to abort.

GuardedSwiftyJSON provides the following protocol

protocol JsonInitializable {
  init?(json: JSON)
  init(json: GuardedJSON)
}

and a default implementation of init?(json: JSON) which automatically calls the proxying initializer and then fails the initialization if any of the required JSON properties are not present.

Nested objects

Often you will have nested JSON objects that you will want to represent as a separate model. The default behavior is for the outer initializer to fail if a nested object is not valid. For example:

struct Outer : JsonInitializable {
  let inner : Inner

  init(json: GuardedJSON) {
    // since the inner json is still a GuardedJSON object in the same context,
    // if any of the properties trying to be extracted are invalid, the outer
    // initialization process will fail.
    inner = Inner(json: json["inner"])
  }
}

If we want an inner object to be optional, we should use the failable initializer of the Inner object:

struct Outer : JsonInitializable {
  let inner : Inner?

  init(json: GuardedJSON) {
    // here we extract the raw json object and call the failable initializer
    inner = Inner(json: json["inner"].rawJson)
  }
}

The same approach can be used to flatten a nested array of objects, where we only want to drop the ones that cannot be deserialized:

struct Outer : JsonInitializable {
  let items: [Inner]

  init(json: GuardedJSON) {
    inner = json["inner"].array.flatMap {
      return Inner(json: $0.rawJson)
    }
  }
}

To be specific, the Outer initializer will fail if the inner key is not present or is not an array. Otherwise the Outer initializer will succeed, and the array will be filled with any valid elements from the JSON.

In this way you can control where you want initialization to fail.

Installation

Carthage

github "wiggzz/GuardedSwiftyJSON"

Cocoapods

pod 'GuardedSwiftyJSON'

Contributing

Pull requests and issues are welcomed.

To run the tests, you first need to install the dependencies using Carthage.

carthage update
You might also like...
Swift-flows - Simplistic hot and cold flow-based reactive observer pattern for Swift… ideal for MVVM architectures

SwiftFlows Simplistic hot and cold flow-based reactive observer pattern for Swif

Elegant HTTP Networking in Swift
Elegant HTTP Networking in Swift

Alamofire is an HTTP networking library written in Swift. Features Component Libraries Requirements Migration Guides Communication Installation Usage

Robust Swift networking for web APIs
Robust Swift networking for web APIs

Conduit Conduit is a session-based Swift HTTP networking and auth library. Within each session, requests are sent through a serial pipeline before bei

Easy to use OAuth 2 library for iOS, written in Swift.
Easy to use OAuth 2 library for iOS, written in Swift.

Heimdallr Heimdallr is an OAuth 2.0 client specifically designed for easy usage. It currently supports the resource owner password credentials grant f

Swift HTTP for Humans
Swift HTTP for Humans

Just is a client-side HTTP library inspired by python-requests - HTTP for Humans. Features Just lets you to the following effortlessly: URL queries cu

Network abstraction layer written in Swift.
Network abstraction layer written in Swift.

Moya 14.0.0 A Chinese version of this document can be found here. You're a smart developer. You probably use Alamofire to abstract away access to URLS

Versatile HTTP Networking in Swift
Versatile HTTP Networking in Swift

Net is a versatile HTTP networking library written in Swift. 🌟 Features URL / JSON / Property List Parameter Encoding Upload File / Data / Stream / M

A type-safe, high-level networking solution for Swift apps
A type-safe, high-level networking solution for Swift apps

What Type-safe network calls made easy Netswift offers an easy way to perform network calls in a structured and type-safe way. Why Networking in Swift

OAuth2 framework for macOS and iOS, written in Swift.
OAuth2 framework for macOS and iOS, written in Swift.

OAuth2 OAuth2 frameworks for macOS, iOS and tvOS written in Swift 5.0. ⤵️ Installation 🛠 Usage 🖥 Sample macOS app (with data loader examples) 📖 Tec

Comments
  • Updated syntax for Swift 3.0

    Updated syntax for Swift 3.0

    I simply used Xcode's swift converter for this. The xcproject file seemed to have already been missing Quick and other things necessary to compile. I did not attempt to fix those. But the code-changes appear to be correct.

    opened by dannys42 2
Releases(0.7.1)
Owner
Will James
Will James
Swift HTTP server using the pre-fork worker model

Curassow Curassow is a Swift Nest HTTP Server. It uses the pre-fork worker model and it's similar to Python's Gunicorn and Ruby's Unicorn. It exposes

Kyle Fuller Archive 397 Oct 30, 2022
DBNetworkStack is a network abstraction for fetching request and mapping them to model objects

DBNetworkStack Main Features ?? Typed network resources ?? Value oriented architecture ?? Exchangeable implementations ?? Extendable API ?? Composable

DB Systel GmbH 33 Jan 10, 2022
A light weight network library with automated model parser for rapid development

Gem A light weight network library with automated model parser for rapid development. Managing all http request with automated model parser calls in a

Albin CR 10 Nov 19, 2022
An easy to integrate Model Based Google Maps Helper (SVHTTPClient, AFNetworking) That lets you Geo Code , Reverse Geocode, Get Directions , Places Autocomplete.

GoogleMapsHelper Read Me in Russian : http://gargo.of.by/googlemapshelper/ A GOOGLE MAPS Helper that help you do multiple tasks like HOW TO USE // usi

Zeeshan Haider 21 Jul 28, 2022
Server-side Swift. The Perfect core toolset and framework for Swift Developers. (For mobile back-end development, website and API development, and more…)

Perfect: Server-Side Swift 简体中文 Perfect: Server-Side Swift Perfect is a complete and powerful toolbox, framework, and application server for Linux, iO

PerfectlySoft Inc. 13.9k Jan 6, 2023
Socket framework for Swift using the Swift Package Manager. Works on iOS, macOS, and Linux.

BlueSocket Socket framework for Swift using the Swift Package Manager. Works on iOS, macOS, and Linux. Prerequisites Swift Swift Open Source swift-5.1

Kitura 1.3k Dec 26, 2022
Swift Express is a simple, yet unopinionated web application server written in Swift

Documentation <h5 align="right"><a href="http://demo.swiftexpress.io/">Live ?? server running Demo <img src="https://cdn0.iconfinder.com/data/icons/

Crossroad Labs 850 Dec 2, 2022
Swift backend / server framework (Pure Swift, Supports Linux)

NetworkObjects NetworkObjects is a #PureSwift backend. This framework compiles for OS X, iOS and Linux and serves as the foundation for building power

Alsey Coleman Miller 258 Oct 6, 2022
Swift-multipart-formdata - MultipartFormData: Build multipart/form-data type-safe in Swift

MultipartFormData Build multipart/form-data type-safe in Swift. A result builder

Felix Herrmann 21 Dec 29, 2022
Approov Integration Examples 0 Jan 26, 2022