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 { }
You might want to make isStringAnInt() a computed property extension String { var isInt: Bool { if let _ = Int(self) { return true } return false } } , then you can do "123". isInt .
Using Int initializer Swift provides the function of integer initializers using which we can convert a string into an Int type. To handle non-numeric strings, we can use nil coalescing using which the integer initializer returns an optional integer.
In Swift, how can I check if a String is alphanumeric, ie, if it contains only one or more alphanumeric characters [a-zA-Z0-9] , excluding letters with diacritics, eg, é.
In Swift, the first property is used to return the first character of a string.
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
Use this function
func isStringAnInt(string: String) -> Bool { return Int(string) != nil }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With