Skip to content

Commit 4dbbc3c

Browse files
authored
Decimal.init(string:) should return nil for invalid Decimal strings (#693)
resolves: rdar://130209835
1 parent 4c8f0f2 commit 4dbbc3c

File tree

2 files changed

+15
-0
lines changed

2 files changed

+15
-0
lines changed

Sources/FoundationEssentials/Decimal/Decimal.swift

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -345,6 +345,11 @@ extension Decimal {
345345
return nil
346346
}
347347
}
348+
if index == stringView.startIndex {
349+
// If we weren't able to process any character
350+
// the entire string isn't a valid decimal
351+
return nil
352+
}
348353
result.compact()
349354
// if we get to this point, and have NaN,
350355
// then the input string was probably "-0"

Tests/FoundationEssentialsTests/DecimalTests.swift

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -258,4 +258,14 @@ final class DecimalTests : XCTestCase {
258258
XCTAssertNotNil(decimal)
259259
XCTAssertEqual(decimal!.description, "3.14")
260260
}
261+
262+
func testStringNoMatch() {
263+
// This test makes sure Decimal returns nil
264+
// if the does not start with a number
265+
var notDecimal = Decimal(string: "A Flamingo's head has to be upside down when it eats.")
266+
XCTAssertNil(notDecimal)
267+
// Same if the number does not appear at the beginning
268+
notDecimal = Decimal(string: "Jump 22 Street")
269+
XCTAssertNil(notDecimal)
270+
}
261271
}

0 commit comments

Comments
 (0)