Skip to content

Commit

Permalink
Merge pull request #105 from SwiftGen/fix/swift-identifier
Browse files Browse the repository at this point in the history
Fix `swiftIdentifier` crash with empty strings
  • Loading branch information
djbe authored Oct 1, 2018
2 parents 1a05285 + 6a981aa commit f823d0f
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 4 deletions.
4 changes: 3 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
5 changes: 2 additions & 3 deletions Sources/StencilSwiftKit/SwiftIdentifier.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 4 additions & 0 deletions Tests/StencilSwiftKitTests/SwiftIdentifierTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,10 @@ class SwiftIdentifierTests: XCTestCase {
SwiftIdentifier.identifier(from: "hello$world^this*contains%a=lot@of<forbidden>chars!does#it/still:work.anyway?"),
"HelloWorldThisContainsALotOfForbiddenCharsDoesItStillWorkAnyway")
}

func testEmptyString() {
XCTAssertEqual(SwiftIdentifier.identifier(from: ""), "")
}
}

extension SwiftIdentifierTests {
Expand Down

0 comments on commit f823d0f

Please sign in to comment.