Yabusa
Yabusa

Reputation: 579

How to check if whether a string is all lowercase?

I've got the code below. I want the string to be capitalized if the user input is all lowercased. Does swift offer this feature? I know in Python is ".islower()". I tried googling, I tried typing .is and seeing what comes up, but no luck.


let holder = PasswordCoreData(entity: PasswordCoreData.entity(), insertInto: context)

if let title = createHolderItem.text {
    holder.item = title

    //here is where I need help
    if holder.item.[islowercased] {
        holder.item = holder.item.capitalized
    }
    holder.username = createHolderUsername.text!
    holder.password = createHolderPassword.text!
}

Upvotes: 0

Views: 1095

Answers (2)

ielyamani
ielyamani

Reputation: 18591

For letters in the english alphabet (from lowercase a to lowercase z) you could verify that title is lowercase by checking that all the Unicode scalars

let scalars = title.compactMap { $0.unicodeScalars.first?.value }

do satisfy this condition:

let isLowerCase = scalars.allSatisfy({ $0 > 96 })  //true

The Unicode scalars of A to Z go from 65 to 90. You can check them this way :

"A".unicodeScalars.first?.value` //65 
"Z".unicodeScalars.first?.value` //90

As to lowercase letters they go from 97 to 122:

"a".unicodeScalars.first?.value  //97 
"z".unicodeScalars.first?.value  //122

For more on Unicode scalars, have a look here.


A more succint solution (suggested by @rmaddy), that covers accented letters and letters from other alphabets, is to check the isLowercase property of all the characters:

let isLowerCase = title.allSatisfy({ $0.isLowercase })

Upvotes: 1

rmaddy
rmaddy

Reputation: 318934

Check if title is equal to the lowercased version of title.

if title == title.lowercased() {
    // It's an all lowercase string
}

You can make a helpful little extension:

extension StringProtocol {
    var isLowercase: Bool {
        return self == self.lowercased()
    }
}

Now use it as:

if title.isLowercase {
}

Upvotes: 4

Related Questions