diff --git a/CHANGELOG.md b/CHANGELOG.md index d0863d75..1503e408 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,7 +14,9 @@ _None_ ### Bug Fixes -_None_ +* `swiftIdentifier`: fix crash on empty string. + [David Jennes](https://github.com/djbe) + [#105](https://github.com/SwiftGen/StencilSwiftKit/pull/105) ### Internal Changes diff --git a/Sources/StencilSwiftKit/SwiftIdentifier.swift b/Sources/StencilSwiftKit/SwiftIdentifier.swift index f1b78268..096b7fb9 100644 --- a/Sources/StencilSwiftKit/SwiftIdentifier.swift +++ b/Sources/StencilSwiftKit/SwiftIdentifier.swift @@ -114,10 +114,9 @@ enum SwiftIdentifier { static func prefixWithUnderscoreIfNeeded(string: String, forbiddenChars exceptions: String = "") -> String { - let (head, _) = identifierCharacterSets(exceptions: exceptions) + guard let firstChar = string.unicodeScalars.first else { return "" } - let chars = string.unicodeScalars - let firstChar = chars[chars.startIndex] + let (head, _) = identifierCharacterSets(exceptions: exceptions) let prefix = !head.longCharacterIsMember(firstChar.value) ? "_" : "" return prefix + string diff --git a/Tests/StencilSwiftKitTests/SwiftIdentifierTests.swift b/Tests/StencilSwiftKitTests/SwiftIdentifierTests.swift index fbcdc61e..c1e4183d 100644 --- a/Tests/StencilSwiftKitTests/SwiftIdentifierTests.swift +++ b/Tests/StencilSwiftKitTests/SwiftIdentifierTests.swift @@ -47,6 +47,10 @@ class SwiftIdentifierTests: XCTestCase { SwiftIdentifier.identifier(from: "hello$world^this*contains%a=lot@ofchars!does#it/still:work.anyway?"), "HelloWorldThisContainsALotOfForbiddenCharsDoesItStillWorkAnyway") } + + func testEmptyString() { + XCTAssertEqual(SwiftIdentifier.identifier(from: ""), "") + } } extension SwiftIdentifierTests {