Last active
December 7, 2021 07:03
-
-
Save kristopherjohnson/2b9c8cbea41c854960fc to your computer and use it in GitHub Desktop.
Swift: determine whether optional String, NSString, or collection is nil or empty
This file contains hidden or 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
import Foundation | |
/** | |
Determine whether Optional collection is nil or an empty collection | |
:param: collection Optional collection | |
:returns: true if collection is nil or if it is an empty collection, false otherwise | |
*/ | |
public func isNilOrEmpty<C: CollectionType>(collection: C?) -> Bool { | |
switch collection { | |
case .Some(let nonNilCollection): return countElements(nonNilCollection) == 0 | |
default: return true | |
} | |
} | |
/** | |
Determine whether Optional NSString is nil or an empty string | |
:param: string Optional NSString | |
:returns: true if string is nil or if it is an empty string, false otherwise | |
*/ | |
public func isNilOrEmpty(string: NSString?) -> Bool { | |
switch string { | |
case .Some(let nonNilString): return nonNilString.length == 0 | |
default: return true | |
} | |
} | |
// String examples (note that a String is a collection) | |
let nilString: String? = nil | |
isNilOrEmpty(nilString) | |
let emptyString: String? = "" | |
isNilOrEmpty(emptyString) | |
let nonEmptyString: String? = "Hello, world!" | |
isNilOrEmpty(nonEmptyString) | |
// NSString examples | |
let nilNSString: NSString? = nil | |
isNilOrEmpty(nilNSString) | |
let emptyNSString: NSString? = "" | |
isNilOrEmpty(emptyNSString) | |
let nonEmptyNSString: NSString? = "Hello, world!" | |
isNilOrEmpty(nonEmptyNSString) | |
// Array examples | |
let nilArray: [Int]? = nil | |
isNilOrEmpty(nilString) | |
let emptyArray: [Int]? = [] | |
isNilOrEmpty(emptyArray) | |
let nonEmptyArray: [Int]? = [0, 1, 2, 3] | |
isNilOrEmpty(nonEmptyArray) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment