SwiftyModel

Getting started

Find your way around, generate your first model, then put it in your project.

The window

A SwiftyModel window has three parts:

  • JSON editor: type or paste JSON. Its title bar has the Paste and Format JSON buttons.
  • Swift result: the generated model. Its title bar has the Copy and Share buttons.
  • Settings column: on the right, controls how the code is written. See Settings.

The two editors can be stacked or placed side by side; switch between them under Layout at the top of the settings column. When you choose side by side, the window widens to fit both.

Generate your first model

  1. Click Paste above the JSON editor to bring in the text on the clipboard, or type or paste straight into the editor.
  2. If the JSON is all on one line, click Format JSON to indent it so it is easier to check.
  3. Enter a name for the top-level type in Model Name in the settings column, such as User. If you leave it empty, NewModel is used.
  4. The Swift result updates as you type. There is no Generate button to press.
  5. Click Copy to put the code on the clipboard, or click the Share button to send it with Mail, Notes and other services.

The top level of the JSON must be an object ({…}) or an array ([…]). When the JSON is invalid, a message above the result says what is wrong and where. The previous result stays visible, but it cannot be copied or shared until the JSON is valid again.

Use the model in your project

Generated code starts with import SwiftyJSON and always includes an init(json: JSON) initializer, so your project needs the SwiftyJSON package. In Xcode, choose File > Add Package Dependencies… and enter https://github.com/SwiftyJSON/SwiftyJSON.

Reading with SwiftyJSON:

SwiftyJSON
import SwiftyJSON

let json = try JSON(data: data)
let user = User(json: json)
print(user.userName)

With the Codable option on, you can also decode with JSONDecoder:

Codable
let user = try JSONDecoder().decode(User.self, from: data)
let encoded = try JSONEncoder().encode(user)

Show and hide the settings column

Once your settings are in place, hide the column to give the code more room:

  • click the sidebar button on the right of the toolbar, or
  • choose View > Hide Settings, or press ⌃⌘S.

Do the same again to show it. Whether the column is hidden, and every setting, are restored the next time you open SwiftyModel.

Windows and saving

Choose File > New Window (⌘N) to work in several windows at once. SwiftyModel keeps running after you close the last window; click its icon in the Dock to open a new one.

The JSON you edited most recently is saved on your Mac and comes back the next time you open SwiftyModel.