Skip to content

Instantly share code, notes, and snippets.

@vibrazy
Created June 28, 2016 22:28
Show Gist options
  • Save vibrazy/1656156e458f620ef3658b067f3d9125 to your computer and use it in GitHub Desktop.
Save vibrazy/1656156e458f620ef3658b067f3d9125 to your computer and use it in GitHub Desktop.
Convenience extension on Optionals to return true or false if the collection is not empty and has elements
var userPreferences: [String]? = [""]
/// Type safe method to check if collection is nil and if not if it has values
func nilOrEmptyCollection<Collection where Collection: CollectionType>(collection: Collection?) -> Bool {
guard let collection = collection else { return true }
return collection.isEmpty
}
/// Extension on Options with constraint to collection type
extension Optional where Wrapped: CollectionType {
func nilOrEmptyCollection() -> Bool {
guard let value = self else { return true }
return value.isEmpty
}
func hasElements() -> Bool {
return !nilOrEmptyCollection()
}
}
/// Version 1
if !nilOrEmptyCollection(userPreferences) {
print("Do something with collection")
}
/// Version 2
if let values = userPreferences where !values.isEmpty {
print("Do something with collection")
}
/// Version 3
var isEmpty = userPreferences?.isEmpty ?? true
if !isEmpty {
print("Do something with collection")
}
/// Version 4
if userPreferences.hasElements() {
print("Do something with collection")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment