Skip to content

Instantly share code, notes, and snippets.

@bokuo-okubo
Last active December 15, 2015 02:58
Show Gist options
  • Save bokuo-okubo/be6eca0902172604bb4d to your computer and use it in GitHub Desktop.
Save bokuo-okubo/be6eca0902172604bb4d to your computer and use it in GitHub Desktop.
func char(str: String) -> ParseFunction {
var letters = Set<Character>(str.characters)
return { (target: String, position: Int) -> ParseResult in
let range = stringRange(target, start: position, advance: 1)
let char: Character = target.substringWithRange(range).characters.first!
if letters.contains(char) {
return (true, [String(char)], position)
} else {
return (false, [nil], position)
}
}
}
/*-----*/
let charParse = char("abcdef")
charParse(target: "apple", position: 0) // -> (true,["a"], 0)
func stringRange(target: String, start: Int, advance: Int) -> Range<String.CharacterView.Index> {
let idx = target.startIndex
let range = Range(start: idx.advancedBy(start),
end: idx.advancedBy(start).advancedBy(advance) )
return range
}
/*---------------------*/
let target = "apple"
let position = 0
let range = stringRange(target, start: position, advance: 1)
let sub = target.substringWithRange(range) // => "a"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment