Created
October 31, 2018 19:37
-
-
Save mattt/a7ee9869001bd8679304186f1655359d to your computer and use it in GitHub Desktop.
This file contains hidden or 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 | |
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