Forked from kristopherjohnson/isNilOrEmpty.swift
Last active
August 29, 2015 14:27
-
-
Save mushu8/be35c93a1e1afc94b22f 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?) -> C? { | |
switch collection { | |
case .Some(let nonNilCollection): return count(nonNilCollection) > 0 ? nonNilCollection : nil | |
default: return nil | |
} | |
} | |
/** | |
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 ? nonNilString : nil | |
default: return nil | |
} | |
} | |
// 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