To check if a string contains only alphabets in Swift, you can use a combination of regular expressions and the allSatisfy
method of the String class.
In this example,
str
with a string value.allSatisfy
method of the string object str
to check if all characters in the string are alphabetic.allSatisfy
method takes a closure that checks if each character is an alphabet using the isLetter
property.import Foundation
let str = "HelloWorld"
let isAlphabetsOnly = str.allSatisfy { $0.isLetter }
print("String contains only alphabets: \(isAlphabetsOnly)")
String contains only alphabets: true
In this example,
str1
with a string value.allSatisfy
method of the string object str1
to check if all characters in the string are alphabetic.allSatisfy
method takes a closure that checks if each character is an alphabet using the isLetter
property.import Foundation
let str1 = "Hello123"
let isAlphabetsOnly = str1.allSatisfy { $0.isLetter }
print("String contains only alphabets: \(isAlphabetsOnly)")
String contains only alphabets: false
In this tutorial, we learned How to Check if String contains only Alphabets in Swift language with well detailed examples.