Skip to content

Instantly share code, notes, and snippets.

@JanX2
Created June 8, 2014 18:19
Show Gist options
  • Save JanX2/a62521c31e04eb741c0e to your computer and use it in GitHub Desktop.
Save JanX2/a62521c31e04eb741c0e to your computer and use it in GitHub Desktop.
Comparison of two approaches: one not using, one using optionals.
/**
* Determine the common prefix elements of two collections.
* @param collection1 First collection.
* @param collection2 Second collection.
* @return The number of elements common to the start of each collection.
*/
func commonPrefixLength<T: Swift.Collection, U: Swift.Collection where
T: Sequence, U: Sequence,
T.GeneratorType.Element: Equatable,
T.GeneratorType.Element == U.GeneratorType.Element>
(collection1: T, collection2: U) -> T.IndexType.DistanceType {
var collection2generator = collection2.generate()
var i: T.IndexType.DistanceType = 0
for element1 in collection1 {
let element2 = collection2generator.next()
if (element1 != element2) {
return i
}
i++
}
return i
}
commonPrefixLength("abX", "abc")
/**
* Determine the common prefix elements of two collections.
* @param collection1 First collection.
* @param collection2 Second collection.
* @return The number of elements common to the start of each collection.
*/
func commonPrefixLength<T: Swift.Collection, U: Swift.Collection where
T: Sequence, U: Sequence,
T.GeneratorType.Element: Equatable,
T.GeneratorType.Element == U.GeneratorType.Element>
(collection1: T, collection2: U) -> T.IndexType.DistanceType {
var collection2generator = collection2.generate()
var i: T.IndexType.DistanceType = 0
for element1 in collection1 {
let optionalElement2 = collection2generator.next()
if let element2 = optionalElement2 {
if (element1 != element2) {
return i
}
}
else {
break
}
}
return i
}
commonPrefixLength("abX", "abc")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment