How do you check if a string contains only digits in Swift

Swift
import Foundation
func checkString(string: String) -> Bool {
let digits = CharacterSet.decimalDigits
let stringSet = CharacterSet(charactersIn: string)
return digits.isSuperset(of: stringSet)
}
print("Check if a string contains only digits")
print("Enter a string: ", terminator: "")
let inputString = readLine()! // readLine() returns an optional String? so we need to unwrap it using ! (force unwrapping) or ? (optional binding). In this case, we know that the user will always enter a value so we can force unwrap it. If you're not sure if the user will enter a value, use optional binding.
if checkString(string: inputString) { // call the function and pass in the inputString as an argument
print("The string contains only digits.")
} else {
print("The string does not contain only digits.")
🤖 Code Explanation
/*
The checkString() function defines a CharacterSet called digits which contains all the decimal digits (0-9). It also defines a CharacterSet called stringSet which contains all the characters in the string passed into the function.
The function returns true if the digits CharacterSet is a superset of the stringSet CharacterSet, meaning that every character in stringSet is also in digits. Otherwise, it returns false.
The main body of the code calls the checkString() function, passing in the inputString as an argument. If the function returns true, it prints "The string contains only digits." Otherwise, it prints "The string does not contain only digits."
*/

More problems solved in Swift



















