FreeformJSON is a tiny data structure that allows you to create and/or access freeform JSON data in a type safe manner, while still enjoying the benefits of the Codable protocol. This can be useful if there are parts of your model that you want to have access to, but don't want the overhead of having a class/struct for it.
import FreeformJSON
struct Post: Codable {
let name: String
let embeddedContent: JSON
}
...
let link = post.embeddedContent["origin"]["link"].stringlet post: JSON = [
"name": "My Post",
"rating": 4,
"hidden": false,
"tags": ["tag1", "tag2"]
]struct Post: Encodable {
let name: String
let rating: Double
let hidden: Bool
let tags: [String]
}
let post = Post(name: "My Post", rating: 4.0, hidden: false, tags: ["tag1", "tag2"])
let postJson = try JSON.fromEncodable(post)
let name = post["name"].string // Optional("My Post")let name = post["name"].string // Optional("My Post")
let notAString = post["rating"].string // nil
let nonExisting = post["nonExisting"].string // nil
let tag = post["tags"][0] // Optional("tag1")
let rawTags = post["tags"].rawValue! as! [String] // ["tag1", "tag2"]FreeformJSON is compatible with Swift 4.x and later. All Apple platforms are supported:
- iOS 9.0+
- macOS 10.9+
- watchOS 2.0+
- tvOS 9.0+
Just drop JSON.swift anywhere in your own project.
Download the repo, drag FreeformJSON.xcodeproj into your own project and link the appropriate target for your platform.
Inside your Podfile:
source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '9.0'
target 'TargetName' do
use_frameworks!
pod 'FreeformJSON'
endInside your Cartfile:
github "fabiorodella/FreeformJSON"
Inside your Package.swift:
// swift-tools-version:4.0
import PackageDescription
let package = Package(
name: "TargetName",
dependencies: [
.package(url: "https://github.com/fabiorodella/FreeformJSON.git", from: "1.0.0"),
],
targets: [
.target(
name: "TargetName",
dependencies: ["FreeformJSON"]),
]
)