Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
One-sided Range operators
postfix operator ..< { }
prefix operator ..< { }
struct RangeStart<I: ForwardIndexType> { let start: I }
struct RangeEnd<I: ForwardIndexType> { let end: I }
postfix func ..<<I: ForwardIndexType>(lhs: I) -> RangeStart<I>
{ return RangeStart(start: lhs) }
prefix func ..<<I: ForwardIndexType>(rhs: I) -> RangeEnd<I>
{ return RangeEnd(end: rhs) }
extension Sliceable {
subscript(r: RangeStart<Self.Index>) -> SubSlice {
return self[r.start..<self.endIndex]
}
subscript(r: RangeEnd<Self.Index>) -> SubSlice {
return self[self.startIndex..<r.end]
}
}
extension Sliceable where Generator.Element: Equatable, SubSlice.Generator.Element == Generator.Element
{
func search<S: SequenceType where S.Generator.Element == Generator.Element>(pat: S) -> Index?
{
return self.indices.indexOf {
self[$0..<].startsWith(pat)
}
}
}
let greeting = "Hello, world"
if let idx = greeting.characters.search(", ".characters) {
print(String(greeting.characters[..<idx]))
}
@a2

This comment has been minimized.

Copy link

commented Jul 21, 2015

Very clever! 👏

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.