Skip to content

Commit f823d0f

Browse files
authored
Merge pull request #105 from SwiftGen/fix/swift-identifier
Fix `swiftIdentifier` crash with empty strings
2 parents 1a05285 + 6a981aa commit f823d0f

File tree

3 files changed

+9
-4
lines changed

3 files changed

+9
-4
lines changed

CHANGELOG.md

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,9 @@ _None_
1414

1515
### Bug Fixes
1616

17-
_None_
17+
* `swiftIdentifier`: fix crash on empty string.
18+
[David Jennes](https://github.com/djbe)
19+
[#105](https://github.com/SwiftGen/StencilSwiftKit/pull/105)
1820

1921
### Internal Changes
2022

Sources/StencilSwiftKit/SwiftIdentifier.swift

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -114,10 +114,9 @@ enum SwiftIdentifier {
114114
static func prefixWithUnderscoreIfNeeded(string: String,
115115
forbiddenChars exceptions: String = "") -> String {
116116

117-
let (head, _) = identifierCharacterSets(exceptions: exceptions)
117+
guard let firstChar = string.unicodeScalars.first else { return "" }
118118

119-
let chars = string.unicodeScalars
120-
let firstChar = chars[chars.startIndex]
119+
let (head, _) = identifierCharacterSets(exceptions: exceptions)
121120
let prefix = !head.longCharacterIsMember(firstChar.value) ? "_" : ""
122121

123122
return prefix + string

Tests/StencilSwiftKitTests/SwiftIdentifierTests.swift

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,10 @@ class SwiftIdentifierTests: XCTestCase {
4747
SwiftIdentifier.identifier(from: "hello$world^this*contains%a=lot@of<forbidden>chars!does#it/still:work.anyway?"),
4848
"HelloWorldThisContainsALotOfForbiddenCharsDoesItStillWorkAnyway")
4949
}
50+
51+
func testEmptyString() {
52+
XCTAssertEqual(SwiftIdentifier.identifier(from: ""), "")
53+
}
5054
}
5155

5256
extension SwiftIdentifierTests {

0 commit comments

Comments
 (0)