Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import Foundation
struct TruthyValue {
var value: Bool?
init(_ value: Bool?) {
self.value = value
}
init(_ value: Int) {
switch value {
case 0:
self.init(false)
case 1:
self.init(true)
default:
self.init(nil)
}
}
init(_ value: String) {
switch value.lowercased() {
case "false", "f", "no", "n", "0":
self.init(false)
case "true", "t", "yes", "y", "1":
self.init(true)
default:
self.init(nil)
}
}
}
extension TruthyValue: Decodable {
enum DecodingError: Error {
case invalidType
}
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if let booleanValue = try? container.decode(Bool.self) {
self.init(booleanValue)
} else if let integerValue = try? container.decode(Int.self) {
self.init(integerValue)
} else if let stringValue = try? container.decode(String.self) {
self.init(stringValue)
} else {
throw DecodingError.invalidType
}
}
}
let json = """
[true, "true", "t", "YES", "y", 1]
""".data(using: .utf8)!
let decoder = JSONDecoder()
let decoded = try decoder.decode([TruthyValue].self, from: json)
let arrayOfTruthValues = decoded.map { $0.value }
arrayOfTruthValues // [true, true, true, true, true, true]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.