Skip to content
This repository has been archived by the owner on May 20, 2021. It is now read-only.

Commit

Permalink
Add Wrap() functions for encoding JSON arrays
Browse files Browse the repository at this point in the history
This commit introduces two new `Wrap()` overloads that return either
an array of JSON dictionaries, or JSON-based NSData that has a root
array object - by passing in an array of objects.
  • Loading branch information
JohnSundell committed Apr 28, 2016
1 parent e12d84f commit 4352752
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 2 deletions.
22 changes: 20 additions & 2 deletions Wrap.swift
Original file line number Diff line number Diff line change
Expand Up @@ -74,15 +74,33 @@ public func Wrap<T>(object: T, dateFormatter: NSDateFormatter? = nil) throws ->
}

/**
* Alternative `Wrap()` implementation that returns JSON-encoded NSData
* Alternative `Wrap()` overload that returns JSON-based `NSData`
*
* See the documentation for the dictionary-based `Wrap()` function for more information
* and customization options.
*/
public func Wrap<T>(object: T, writingOptions: NSJSONWritingOptions? = nil, dateFormatter: NSDateFormatter? = nil) throws -> NSData {
return try Wrapper(dateFormatter: dateFormatter).wrap(object, writingOptions: writingOptions ?? [])
}

/**
* Alternative `Wrap()` overload that encodes an array of objects into an array of dictionaries
*
* See the documentation for the dictionary-based `Wrap()` function for more information
*/
public func Wrap<T>(objects: [T], dateFormatter: NSDateFormatter? = nil) throws -> [WrappedDictionary] {
return try objects.map({ try Wrap($0) })
}

/**
* Alternative `Wrap()` overload that encodes an array of objects into JSON-based `NSData`
*
* See the documentation for the dictionary-based `Wrap()` function for more information
*/
public func Wrap<T>(objects: [T], writingOptions: NSJSONWritingOptions? = nil, dateFormatter: NSDateFormatter? = nil) throws -> NSData {
let dictionaries: [WrappedDictionary] = try Wrap(objects)
return try NSJSONSerialization.dataWithJSONObject(dictionaries, options: writingOptions ?? [])
}

/**
* Protocol providing the main customization point for Wrap
*
Expand Down
18 changes: 18 additions & 0 deletions WrapTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -659,6 +659,24 @@ class WrapTests: XCTestCase {
XCTFail(error.toString())
}
}

func testWrappingArray() {
struct Model {
let string: String
}

do {
let models = [Model(string: "A"), Model(string: "B"), Model(string: "C")]
let wrapped: [WrappedDictionary] = try Wrap(models)
XCTAssertEqual(wrapped.count, 3)

try VerifyDictionary(wrapped[0], againstDictionary: ["string" : "A"])
try VerifyDictionary(wrapped[1], againstDictionary: ["string" : "B"])
try VerifyDictionary(wrapped[2], againstDictionary: ["string" : "C"])
} catch {
XCTFail(error.toString())
}
}
}

// MARK: - Mocks
Expand Down

0 comments on commit 4352752

Please sign in to comment.