[SOLVED] Check if a String is alphanumeric in Swift

Issue

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, é.

Solution

extension String {
    var isAlphanumeric: Bool {
        return !isEmpty && range(of: "[^a-zA-Z0-9]", options: .regularExpression) == nil
    }
}

"".isAlphanumeric        // false
"abc".isAlphanumeric     // true
"123".isAlphanumeric     // true
"ABC123".isAlphanumeric  // true
"iOS 9".isAlphanumeric   // false

Answered By – ma11hew28

Answer Checked By – Clifford M. (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *