Skip to content

Instantly share code, notes, and snippets.

@samuelbeek
Created November 17, 2015 15:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save samuelbeek/b9972aadc0fcc792eeee to your computer and use it in GitHub Desktop.
Save samuelbeek/b9972aadc0fcc792eeee to your computer and use it in GitHub Desktop.
Check if string contains number or whitespace
import Foundation
extension String {
func containsNumbers() -> Bool {
// check if there's a range for a number
let range = self.rangeOfCharacterFromSet(.decimalDigitCharacterSet())
// range will be nil if no whitespace is found
if let _ = range {
return true
} else {
return false
}
}
func containsWhiteSpace() -> Bool {
// check if there's a range for a whitespace
let range = self.rangeOfCharacterFromSet(.whitespaceCharacterSet())
// range will be nil if no whitespace is found
if let _ = range {
return true
} else {
return false
}
}
}
let string = "h21312312al112312lo"
print(string.containsNumbers())
@Gatada
Copy link

Gatada commented May 23, 2018

Why not change those methods to dynamic vars?

@zapko
Copy link

zapko commented Jul 30, 2018

And make them just:

return rangeOfCharacterFromSet(.whatevercharaterset()) != nil

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment