Merge pull request #44 from JohnSundell/optional-pattern-matching

Support switch statements with nil pattern matching
This commit is contained in:
John Sundell 2019-03-09 13:12:34 +01:00 committed by GitHub
commit 74c3b8af27
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 49 additions and 0 deletions

View File

@ -221,6 +221,15 @@ private extension SwiftGrammar {
func matches(_ segment: Segment) -> Bool {
if segment.tokens.next == ":" {
// Nil pattern matching inside of a switch statement case
if segment.tokens.current == "nil" {
guard let previousToken = segment.tokens.previous else {
return false
}
return previousToken.isAny(of: "case", ",")
}
guard segment.tokens.current == "default" else {
return false
}

View File

@ -202,6 +202,45 @@ final class StatementTests: SyntaxHighlighterTestCase {
])
}
func testSwitchStatementWithOptional() {
let components = highlighter.highlight("""
switch anOptional {
case nil: break
case "value"?: break
default: break
}
""")
XCTAssertEqual(components, [
.token("switch", .keyword),
.whitespace(" "),
.plainText("anOptional"),
.whitespace(" "),
.plainText("{"),
.whitespace("\n"),
.token("case", .keyword),
.whitespace(" "),
.token("nil", .keyword),
.plainText(":"),
.whitespace(" "),
.token("break", .keyword),
.whitespace("\n"),
.token("case", .keyword),
.whitespace(" "),
.token("\"value\"", .string),
.plainText("?:"),
.whitespace(" "),
.token("break", .keyword),
.whitespace("\n"),
.token("default", .keyword),
.plainText(":"),
.whitespace(" "),
.token("break", .keyword),
.whitespace("\n"),
.plainText("}")
])
}
func testForStatementWithStaticProperty() {
let components = highlighter.highlight("for value in Enum.allCases { }")
@ -306,6 +345,7 @@ extension StatementTests {
("testSwitchStatementWithAssociatedValues", testSwitchStatementWithAssociatedValues),
("testSwitchStatementWithFallthrough", testSwitchStatementWithFallthrough),
("testSwitchStatementWithTypePatternMatching", testSwitchStatementWithTypePatternMatching),
("testSwitchStatementWithOptional", testSwitchStatementWithOptional),
("testForStatementWithStaticProperty", testForStatementWithStaticProperty),
("testForStatementWithContinue", testForStatementWithContinue),
("testRepeatWhileStatement", testRepeatWhileStatement)