How can I check to see if a string contains characters of whitespace/alphanumeric/etc?

Use NSCharacter on the entire string,not character-by-character:

let whitespace = NSCharacterSet.whitespaceCharacterSet()

let phrase = "Test case"
let range = phrase.rangeOfCharacterFromSet(whitespace)

// range will be nil if no whitespace is found
if let test = range {
    println("whitespace found")
}
else {
    println("whitespace not found")
}

Output:

whitespace found

Shorter extension (swift 4.1)

extension String {
    var containsWhitespace : Bool {
        return(self.rangeOfCharacter(from: .whitespacesAndNewlines) != nil)
    }
}

You can change the .whitespacesAndNewlines with any other CharacterSet like this:

extension String {
    var containsDigits : Bool {
        return(self.rangeOfCharacter(from: CharacterSet.decimalDigits) != nil)
    }
}

I created a String extension that does exactly this, hope it's useful.

extension String {
    func containsWhitespaceAndNewlines() -> Bool {
        return rangeOfCharacter(from: .whitespacesAndNewlines) != nil
    }
}

// Usage
"hello, world!".containsWhitespaceAndNewlines() // true
"hello,world!".containsWhitespaceAndNewlines() // false

Tags:

Ios

Swift

Ctype