Author Topic: How do I check for an empty or nil string in Swift?  (Read 6860 times)

kjmcneish

  • Administrator
  • *****
  • Posts: 719
    • View Profile
How do I check for an empty or nil string in Swift?
« on: May 29, 2015, 02:19:05 PM »
Here's an extension you can add to the String class that checks for an empty (after trimming whitespace) or nil string:

Code: [Select]
extension String {
   public static func isNilOrEmpty(string: String?) -> Bool {
       
        switch string?.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) {
        case .Some(let nonNilString):
            return nonNilString.isEmpty
        default:
            return true
        }
    }
}

You can use it like this:

Code: [Select]
var isEmpty = String.isNilOrEmpty(myString)
All the best!
Kevin McNeish
Author of Learn to Code in Swift: https://itunes.apple.com/us/book/learn-to-code-in-swift/id942956811?mt=11