Created
January 31, 2020 13:29
-
-
Save rolandkakonyi/0878fce907c0914fa3ac33cc57786696 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
protocol DefaultRawValueDecodable: RawRepresentable, Decodable { | |
static var defaultValue: Self { get } | |
} | |
extension DefaultRawValueDecodable where RawValue: Decodable { | |
init(from decoder: Decoder) throws { | |
let container = try decoder.singleValueContainer() | |
let stringValue = try container.decode(RawValue.self) | |
self = Self(rawValue: stringValue) ?? Self.defaultValue | |
} | |
} | |
import XCTest | |
class DefaultRawValueDecodableTests: XCTestCase { | |
func testDecode_actualValue() throws { | |
let json = """ | |
{ | |
"enumProperty": "existing value" | |
} | |
""" | |
let decoder = JSONDecoder() | |
let decodedValue = try decoder.decode(Wrapper.self, from: json.data(using: .utf8)!) | |
XCTAssertEqual(decodedValue.enumProperty, TestDefaultRawValueDecodable.existingValue, "actual value should be decoded") | |
} | |
func testDecode_defaultValue() throws { | |
let json = """ | |
{ | |
"enumProperty": "some other value" | |
} | |
""" | |
let decoder = JSONDecoder() | |
let decodedValue = try decoder.decode(Wrapper.self, from: json.data(using: .utf8)!) | |
XCTAssertEqual(decodedValue.enumProperty, TestDefaultRawValueDecodable.unknown, "default value should be decoded") | |
} | |
enum TestDefaultRawValueDecodable: String, DefaultRawValueDecodable { | |
case existingValue = "existing value" | |
case unknown | |
static var defaultValue: TestDefaultRawValueDecodable = .unknown | |
} | |
struct Wrapper: Decodable { | |
let enumProperty: TestDefaultRawValueDecodable | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment