Skip to content

Instantly share code, notes, and snippets.

@mattt
Created October 31, 2018 19:37
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattt/a7ee9869001bd8679304186f1655359d to your computer and use it in GitHub Desktop.
Save mattt/a7ee9869001bd8679304186f1655359d to your computer and use it in GitHub Desktop.
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