• Stars
    star
    784
  • Rank 55,707 (Top 2 %)
  • Language
    Swift
  • License
    Other
  • Created over 9 years ago
  • Updated almost 4 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

✌ Convert anything into anything in one operation; JSON data into class instances, hex strings into UIColor/NSColor, y/n strings to booleans, arrays and dictionaries of these; anything you can make sense of!

JSONHelper CocoaPods CocoaPods

Build Status CocoaPods Gitter

Convert anything into anything in one operation; hex strings into UIColor/NSColor, JSON strings into class instances, y/n strings to booleans, arrays and dictionaries of these; anything you can make sense of!

Latest version requires iOS 8+ and Xcode 7.3+

GitAds

Table of Contents

  1. Installation
  2. The <-- Operator
  3. Convertible Protocol
  4. Deserializable Protocol (with JSON deserialization example)
  5. Serializable Protocol

Installation

Add the following line in your Podfile.

pod "JSONHelper"

Add the following line to your Cartfile.

github "isair/JSONHelper"

Then do carthage update. After that, add the framework to your project.

The <-- Operator

The <-- operator takes the value on its right hand side and tries to convert it into the type of the value on its left hand side. If the conversion fails, an error is logged on debug builds. If it's successful, the value of the left hand side variable is overwritten. It's chainable as well.

If the right hand side value is nil or the conversion fails, and the left hand side variable is an optional, then nil is assigned to it. When the left hand side is non-optional, the current value of the left hand side variable is left untouched.

Using this specification let's assume you have a dictionary response that you retrieved from some API with hex color strings in it, under the key colors, that you want to convert into an array of UIColor instances. Also, to fully use everything we know, let's also assume that we want to have a default value for our color array in case the value for the key we're looking for does not exist (is nil).

var colors = [UIColor.blackColor(), UIColor.whiteColor()]
// Assume we have response { "colors": ["#aaa", "#b06200aa"] }
colors <-- response[colorsKey]

Convertible Protocol

If your type is a simple value-like type, adopting the Convertible protocol is the way to make your type work with the <-- operator.

Example:

struct Vector2D: Convertible {
  var x: Double = 0
  var y: Double = 0

  init(x: Double, y: Double) {
    self.x = x
    self.y = y
  }

  static func convertFromValue<T>(value: T?) throws -> Self? {
    guard let value = value else { return nil }

    if let doubleTupleValue = value as? (Double, Double) {
      return self.init(x: doubleTupleValue.0, y: doubleTupleValue.1)
    }

    throw ConversionError.UnsupportedType
  }
}
var myVector: Vector2D?
myVector <-- (1.0, 2.7)

Deserializable Protocol

While you can basically adopt the Convertible protocol for any type, if your type is always converted from a dictionary or a JSON string then things can get a lot easier with the Deserializable protocol.

Example:

class User: Deserializable {
  static let idKey = "id"
  static let emailKey = "email"
  static let nameKey = "name"
  static let avatarURLKey = "avatar_url"

  private(set) var id: String?
  private(set) var email: String?
  private(set) var name = "Guest"
  private(set) var avatarURL = NSURL(string: "https://mysite.com/assets/default-avatar.png")

  required init(dictionary: [String : AnyObject]) {
    id <-- dictionary[User.idKey]
    email <-- dictionary[User.emailKey]
    name <-- dictionary[User.nameKey]
    avatarURL <-- dictionary[User.avatarURLKey]
  }
}
var myUser: User?
user <-- apiResponse["user"]

Serializable Protocol

// Serialization is coming soon. I'll probably not add a new protocol and just rename and update the Deserializable protocol and turn it into a mixin.

More Repositories

1

ManualLayout

βœ‚ Easy to use and flexible library for manually laying out views and layers for iOS and tvOS. Supports AsyncDisplayKit.
Swift
281
star
2

dotfiles

πŸ–₯️ Backup your packages, apps, and configurations directly to git in the form of profiles. Set up any new machine using a profile in one line. Share profiles between multiple machines. Configure auto update, clean-up, and back-up. Works for all linux flavors, Mac OS, and Windows.
Shell
79
star
3

tensorflow-load-csv

πŸ€– TensorFlow.js CSV loading on steroids. Clean up, normalise, transform, shuffle, and split your data all in a handful of lines and dive right into the fun parts of ML.
TypeScript
49
star
4

react-native-smart-assets

βœ… Automatically generate an Images module from your image assets. Converts intelligently (e.g. PDF to @2x, @3x etc).
Shell
41
star
5

OpenChess

A cross-platform chess game.
Java
21
star
6

notepad-pwa

πŸ—’οΈ Lightweight, simple text editor for all platforms. Supports multiple tabs and auto saving. Visit the website and add it to your computer desktop, phone homescreen; use like a native app.
Vue
19
star
7

jedi-academy-server

Jedi Academy server solution without any headaches. With RTVRTM. Dockerized.
Python
11
star
8

Toasty

App extension compatible Toast library for iOS, and tvOS. Written in Swift.
Swift
4
star
9

youtubekapatildimi

A simple python web app that checks if youtube is accessible from Turkey.
HTML
3
star
10

jacontrol-desktop

A cross-platform, portable rcon GUI tool built for Jedi Academy using JDK 9.
Java
3
star
11

takt-kids

Open source convention management system. No longer maintained.
Python
1
star
12

isair.github.io

My personal website.
Vue
1
star
13

flutter-functional-components-with-hooks-demo

A simple Flutter app with functional components and hooks. Done quickly to learn the basics of Flutter.
Dart
1
star