Last active
December 15, 2015 02:58
-
-
Save bokuo-okubo/be6eca0902172604bb4d to your computer and use it in GitHub Desktop.
This file contains 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
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) |
This file contains 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
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