Created
October 11, 2017 07:15
-
-
Save santoshrajan/8cb786802f37a352d148de0dda3505ae to your computer and use it in GitHub Desktop.
String Parser in Swift 4
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
typealias ParseResult = (output: Any, rest: Substring)? | |
func stringParser(input: Substring) -> ParseResult { | |
if input[input.startIndex] != "\"" { | |
return nil | |
} | |
var isEscape = true | |
func inspectChar(char: Character) -> Bool { | |
if char == "\"" && !isEscape { | |
return true | |
} | |
if char == "\\" { | |
isEscape = true | |
} else { | |
isEscape = false | |
} | |
return false | |
} | |
if let index = input.index(where: inspectChar) { | |
return (input[input.index(after: input.startIndex)...input.index(before: index)], | |
input[input.index(after: index)...]) | |
} | |
return nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment