Skip to content

Instantly share code, notes, and snippets.

@iosdevzone
Last active January 19, 2018 23:34
Show Gist options
  • Save iosdevzone/55a1c742efb603cb7d57c8dd5c41887f to your computer and use it in GitHub Desktop.
Save iosdevzone/55a1c742efb603cb7d57c8dd5c41887f to your computer and use it in GitHub Desktop.
RecursiveSubSequence is a protocol I've found useful.
protocol RecursiveSubSequence: Sequence where SubSequence: RecursiveSubSequence { }
extension String: RecursiveSubSequence { }
extension Substring: RecursiveSubSequence { }
extension Array: RecursiveSubSequence {}
extension ArraySlice: RecursiveSubSequence {}
func process<T>(_ value: T) -> T { return value }
func count<S: RecursiveSubSequence>(_ s: S) -> Int {
guard let head = (s.first { _ in true }) else { return 0 }
process(head) // supress compiler warning
let tail = s.dropFirst()
return count(tail) + 1
}
count("aa") // -> 2
count([1,2,3]) // -> 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment