Skip to content

Instantly share code, notes, and snippets.

@arielelkin
Forked from natecook1000/isNullOrEmpty.swift
Created February 17, 2021 16:57
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 arielelkin/337cb80c28bbf09d646651d5b4755b81 to your computer and use it in GitHub Desktop.
Save arielelkin/337cb80c28bbf09d646651d5b4755b81 to your computer and use it in GitHub Desktop.
protocol StringType {
var isEmpty: Bool { get }
}
extension String : StringType { }
extension Optional where Wrapped: StringType {
var isNullOrEmpty: Bool {
return self?.isEmpty ?? true
}
}
extension Optional where Wrapped: CollectionType {
var isNullOrEmpty: Bool {
return self?.isEmpty ?? true
}
}
// Strings:
let strs: [String?] = [nil, "", "Hello!"]
for s in strs {
if s.isNullOrEmpty {
print("null or empty string: \(s)")
}
}
// Collections:
let colls: [[Int]?] = [nil, [], [1, 2, 3]]
for c in colls {
if c.isNullOrEmpty {
print("null or empty collection: \(c)")
}
}
let filtered = colls.map({ $0?.lazy.filter({ $0 > 3 }) })
for c in filtered {
if c.isNullOrEmpty {
print("null or empty filtered collection: \(c)")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment