Skip to content

Commit 524dc69

Browse files
author
Robert Thompson
committed
slightly refactor LosslessStringConvertible initializer as per PR feedback
1 parent ea2b6f8 commit 524dc69

File tree

1 file changed

+15
-12
lines changed

1 file changed

+15
-12
lines changed

Sources/BigInt/BigInt.swift

Lines changed: 15 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -4,29 +4,32 @@
44
//
55
// Created by Robert Thompson on 2/4/19.
66
//
7-
fileprivate let digitsAndDash = Set("-0123456789")
87

98
public struct BigInt: BinaryInteger, SignedNumeric, SignedInteger, CustomStringConvertible, LosslessStringConvertible, Hashable {
109

1110
public private(set) var words: Array<UInt>
1211

1312
public init?(_ description: String) {
14-
guard description.allSatisfy({ digitsAndDash.contains($0) }) else { return nil }
15-
var result: BigInt = 0
13+
guard let firstCharacter = description.first else { return nil }
14+
1615
var description = description
1716
let isNegative: Bool
18-
if description.first == "-" {
19-
guard description.count > 1 else { return nil }
20-
21-
isNegative = true
22-
description.removeFirst()
23-
} else {
24-
isNegative = false
17+
if description.count > 1 {
18+
if firstCharacter == "-" {
19+
isNegative = true
20+
description.removeFirst()
21+
} else if firstCharacter == "+" {
22+
description.removeFirst()
23+
}
2524
}
2625

26+
let digitsAndDash = Set("0123456789")
27+
guard description.allSatisfy({ digitsAndDash.contains($0) }) else { return nil }
28+
29+
var result: BigInt = 0
2730
for (i, char) in description.reversed().enumerated() {
28-
guard let digitInt = Int(String(char)) else { return nil }
29-
result += BigInt(digitInt) * pow(10, BigInt(i))
31+
// We're ok to force unwrap here because of the guard above.
32+
result += BigInt(char.wholeNumberValue!) * pow(10, BigInt(i))
3033
}
3134

3235
if isNegative {

0 commit comments

Comments
 (0)