Skip to content

Commit

Permalink
Remove value wrapper from CodableBridge
Browse files Browse the repository at this point in the history
Fixes #32
  • Loading branch information
sindresorhus committed Oct 4, 2023
1 parent 55ec930 commit daf8d16
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 6 deletions.
9 changes: 3 additions & 6 deletions Sources/Defaults/Defaults+Bridge.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,10 @@ extension Defaults.CodableBridge {
}

do {
// Some codable values like URL and enum are encoded as a top-level
// string which JSON can't handle, so we need to wrap it in an array
// We need this: https://forums.swift.org/t/allowing-top-level-fragments-in-jsondecoder/11750
let jsonEncoder = JSONEncoder()
jsonEncoder.outputFormatting = .sortedKeys
let data = try jsonEncoder.encode([value])
return String(String(data: data, encoding: .utf8)!.dropFirst().dropLast())
let data = try jsonEncoder.encode(value)
return String(data: data, encoding: .utf8)
} catch {
print(error)
return nil
Expand All @@ -30,7 +27,7 @@ extension Defaults.CodableBridge {
return nil
}

return [Value].init(jsonString: "[\(object)]")?.first
return Value.init(jsonString: object)

Check warning on line 30 in Sources/Defaults/Defaults+Bridge.swift

View workflow job for this annotation

GitHub Actions / lint

Explicit Init Violation: Explicitly calling .init() should be avoided (explicit_init)

Check warning on line 30 in Sources/Defaults/Defaults+Bridge.swift

View workflow job for this annotation

GitHub Actions / lint

Explicit Init Violation: Explicitly calling .init() should be avoided (explicit_init)
}
}

Expand Down
13 changes: 13 additions & 0 deletions Tests/DefaultsTests/DefaultsCodableTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,19 @@ final class DefaultsCodableTests: XCTestCase {
XCTAssertFalse(Defaults[key]["0"]?[1].isUnicorn ?? true)
}

func testCodableAndRawRepresentable() {
struct Unicorn: Codable, RawRepresentable, Defaults.Serializable {
var rawValue: String
}

let fixture = Unicorn(rawValue: "x")

let key = Defaults.Key<Unicorn?>("independentKey_codableAndRawRepresentable")
Defaults[key] = fixture
XCTAssertEqual(Defaults[key]?.rawValue, fixture.rawValue)
XCTAssertEqual(UserDefaults.standard.string(forKey: key.name), #""\#(fixture.rawValue)""#)
}

func testType() {
XCTAssertTrue(Defaults[.codable].isUnicorn)
Defaults[.codable] = Unicorn(isUnicorn: false)
Expand Down

0 comments on commit daf8d16

Please sign in to comment.