SwiftDeveloper SwiftDeveloper - 3 months ago 13
iOS Question

How to use uppercaseString, lowercaseString in Swift

I have strings and i want to convert to

uppercaseString, lowercaseString
with
only letters


My strings;

let uppers = " Hello*im ; + Upper+String "
let lowers = " Hello*im ; + Lower+String "
print(uppers)
print(lowers)


Thank you !

Answer

You can use Set for that.

let uppers  = " Hello*im ; + Upper+String "
let lowers  = " Hello*im ; + Lower+String "
let allowChars : Set<Character> = Set("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLKMNOPQRSTUVWXYZ1234567890".characters)
let upperStr = String(uppers.characters.filter {allowChars.contains($0) }).uppercaseString
let lowerStr = String(lowers.characters.filter {allowChars.contains($0) }).lowercaseString
print(upperStr)
print(lowerStr)

Edit: To allow space also add space inside the Set characters with other character

let allowChars : Set<Character> = Set("abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLKMNOPQRSTUVWXYZ1234567890".characters)