Skip to content

Instantly share code, notes, and snippets.

@tapi
Created June 4, 2014 05:41
Show Gist options
  • Select an option

  • Save tapi/c88175a020a232eb8a54 to your computer and use it in GitHub Desktop.

Select an option

Save tapi/c88175a020a232eb8a54 to your computer and use it in GitHub Desktop.
Generic types broken into separate lines
func anyCommonElements <T, U where T: Sequence, U: Sequence, T.GeneratorType.Element: Equatable, T.GeneratorType.Element == U.GeneratorType.Element> (lhs: T, rhs: U) -> Bool {
for lhsItem in lhs {
for rhsItem in rhs {
if lhsItem == rhsItem {
return true
}
}
}
return false
}
anyCommonElements([1, 2, 3], [3])
func anyCommonElements
<T, U where T: Sequence, U: Sequence, T.GeneratorType.Element: Equatable, T.GeneratorType.Element == U.GeneratorType.Element>
(lhs: T, rhs: U) -> Bool
{
for lhsItem in lhs {
for rhsItem in rhs {
if lhsItem == rhsItem {
return true
}
}
}
return false
}
anyCommonElements([1, 2, 3], [3])
@x-goose-x
Copy link
Copy Markdown

If you wanted to go buck wild you could decompose it even further to roughly one constraint per line (assuming the whitespace doesn't make swift sad)

func anyCommonElements
    <T, U where
       T: Sequence, U: Sequence, 
       T.GeneratorType.Element: Equatable, 
       T.GeneratorType.Element == U.GeneratorType.Element>
    (lhs: T, rhs: U) -> Bool 
    {
    for lhsItem in lhs {
        for rhsItem in rhs {
            if lhsItem == rhsItem {
                return true
            }
        }
    }
    return false
}

@tapi
Copy link
Copy Markdown
Author

tapi commented Dec 3, 2015

@angusiguess Good call, Looks like this is what apple does internally https://github.com/apple/swift/blob/master/stdlib/public/core/Arrays.swift.gyb#L690-L693

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment