Small helpers that remove the boilerplate of reading and writing Codable values as JSON files.
- Encode any
Encodablevalue to a file URL, or to a filename in a standard directory (Documents by default). - Decode any
Decodablevalue from a file URL or filename, as aResultor an optional. - Writes are atomic.
- Optional
NCCCodingCodableconformance addsencode(to:)/init?(from:)helpers directly on your types.
- iOS 12+ / macOS 10.15+
- Swift 5.2+
Add the package with Swift Package Manager:
dependencies: [
.package(url: "https://github.com/drewster99/NCCCoding.git", from: "1.1.0")
]Then add "NCCCoding" to your target's dependencies.
import Foundation
import NCCCoding
struct Settings: Codable {
var username: String
var volume: Double
}
let settings = Settings(username: "andrew", volume: 0.8)
// Write to Documents/settings.json
if let error = NCCCoding.encode(settings, filename: "settings.json") {
print("Save failed: \(error.localizedDescription)")
}
// Read it back, keeping the error
let result: Result<Settings, Error> = NCCCoding.decode(filename: "settings.json")
switch result {
case .success(let loaded):
print(loaded.username)
case .failure(let error):
print("Load failed: \(error.localizedDescription)")
}
// Or read it back as an optional (nil on any failure)
let maybeSettings: Settings? = NCCCoding.decode(filename: "settings.json", in: .cachesDirectory)
// Explicit file URLs work too
let url = FileManager.default.temporaryDirectory.appendingPathComponent("settings.json")
let encodeError = NCCCoding.encode(settings, to: url)
let fromURL: Result<Settings, Error> = NCCCoding.decode(url)struct Profile: Codable, NCCCodingCodable {
var name: String
}
let profile = Profile(name: "Andrew")
let saveError = profile.encode(filename: "profile.json") // Error? (nil on success)
let loaded = Profile(from: "profile.json") // Profile? (nil on any failure)- Directories: filename-based APIs resolve the first matching directory in the user domain and create it if it does not exist. Filenames are appended as-is; no extension is added.
- Errors:
ResultandError?APIs return the underlyingEncodingError,DecodingErroror Cocoa file error unchanged, except when the directory cannot be resolved, which returnsNCCCoding.NCCCodingError.unableToFindSearchPathDirectory. The optional-returning APIs returnnilfor every failure, so use theResultAPIs when you need to tell a missing file from corrupt data. Failures are also logged withos_log(error level, private). - Dates: encoded and decoded as ISO 8601 strings. Encoding keeps whole seconds only, so fractional seconds are lost on a round trip.
- Non-finite floats:
Double.infinity,-Double.infinityandDouble.nanare stored as the strings"+Infinity","-Infinity"and"NaN".
MIT. See LICENSE.