Reputation: 13592
I have a TextField which I want to verify if the inputted text is an integer. How could I do this?
I want to write a function like this:
func isStringAnInt(string: String) -> Bool {
}
Upvotes: 33
Views: 32218
Reputation: 15963
You can also use following extension method that use a different logic than all mentioned answers
extension String {
var isStringAnInt: Bool {
return !isEmpty && self.rangeOfCharacter(from: CharacterSet.decimalDigits.inverted) == nil
}
Upvotes: 1
Reputation: 17
if s is String {
print("Yes, it's a String")
} else if s is Int {
print("It is Integer")
} else {
//some other check
}
Upvotes: -3
Reputation: 59496
You can also add to String
a computed property.
The logic inside the computed property is the same described by OOPer
extension String {
var isInt: Bool {
return Int(self) != nil
}
}
"1".isInt // true
"Hello world".isInt // false
"".isInt // false
Upvotes: 71
Reputation: 5039
You can check like this
func isStringAnInt(stringNumber: String) -> Bool {
if let _ = Int(stringNumber) {
return true
}
return false
}
OR
you can create an extension for String. Go to File -> New File -> Swift File
And in your newly created Swift file you can write
extension String
{
func isStringAnInt() -> Bool {
if let _ = Int(self) {
return true
}
return false
}
}
In this way you will be able to access this function in your whole project like this
var str = "123"
if str.isStringAnInt() // will return true
{
// Do something
}
Upvotes: 1
Reputation: 47886
Use this function
func isStringAnInt(string: String) -> Bool {
return Int(string) != nil
}
Upvotes: 27