Last active
September 1, 2015 10:06
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)") | |
}) | |
} | |
} |
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
I have an
NSManagedObject
subclass calledCategory
and now if I have an Array or Set ofCategory
objects I can callcategorySet.joinNamesWithSeparator(", ")
and get a comma separated list of the category names, wherename
is aString?
property.How very cool!