Skip to content

Instantly share code, notes, and snippets.

@atetlaw
Last active September 1, 2015 10:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save atetlaw/645edef49d3d1a40ef3e to your computer and use it in GitHub Desktop.
Save atetlaw/645edef49d3d1a40ef3e to your computer and use it in GitHub Desktop.
Swift extensions are cool. You can add special support to all SequenceTypes for your types.
extension SequenceType where Generator.Element == Category {
func joinNamesWithSeparator(separator: String) -> String {
return self.reduce("", combine: { ( combinedString: String, cat: Category) in
guard let name = cat.name else {
return combinedString
}
return combinedString + (combinedString.isEmpty ? name : "\(separator)\(name)")
})
}
}
@atetlaw
Copy link
Author

atetlaw commented Sep 1, 2015

I have an NSManagedObject subclass called Category and now if I have an Array or Set of Category objects I can call categorySet.joinNamesWithSeparator(", ") and get a comma separated list of the category names, where name is a String? property.

How very cool!

@atetlaw
Copy link
Author

atetlaw commented Sep 1, 2015

You could also write that reduce call like this:

return self.reduce("") {
    if let name = $1.name {
        return $0 + ($0.isEmpty ? name : "\(separator)\(name)")
    } else {
        return $0
    }
}

If you don't mind the $0, $1

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