Skip to content

Commit

Permalink
Improve boolean string mapping
Browse files Browse the repository at this point in the history
Consider "true" and "1" to be equal to true and "false", "0" to be
false when mapping booleans.

Otherwise return nil.
  • Loading branch information
zenangst committed May 11, 2017
1 parent e012bb1 commit e2b7900
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 1 deletion.
9 changes: 8 additions & 1 deletion Sources/Shared/Extensions/Dictionary+Tailor.swift
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,14 @@ public extension Dictionary {
}

if let string = self[key] as? String {
return string == "true" ? true : false

if ["true", "1"].contains(string.lowercased()) {
return true
} else if ["false", "0"].contains(string.lowercased()) {
return false
}

return nil
} else if let number = self[key] as? NSNumber {
return number.boolValue
} else if let boolean = self[key] as? Bool {
Expand Down
4 changes: 4 additions & 0 deletions TailorTests/Shared/DefaultTypesMappingTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ class TestMappingDefaultTypes: QuickSpec {
"float": 2.5,
"bool" : true,
"string_bool" : "true",
"string_number_bool" : "1",
"string": "1.25",
"array" : [
"foo", "bar", "baz"
Expand Down Expand Up @@ -44,6 +45,7 @@ class TestMappingDefaultTypes: QuickSpec {

expect(dictionary.value(forKey: "bool", ofType: Bool.self)).to(equal(true))
expect(dictionary.value(forKey: "string_bool", ofType: Bool.self)).to(equal(true))
expect(dictionary.value(forKey: "string_number_bool", ofType: Bool.self)).to(equal(true))

expect(dictionary.string("string")).to(equal("1.25"))

Expand All @@ -67,6 +69,8 @@ class TestMappingDefaultTypes: QuickSpec {
expect(dictionary.int("string")).to(equal(1))
expect(dictionary.string("string")).to(equal("1.25"))

expect(dictionary.boolean("string_number_bool")).to(equal(true))

}
}
}
Expand Down

0 comments on commit e2b7900

Please sign in to comment.