Reputation: 830
Is there any specific API to get the next alphabet of a character?
Example:
if
"Somestring".characters.first
results in"S"
, then should return"T"
If there's none I guess I have to iterate through a collection of alphabet and return the next character in order. Or is there any other better solution?
Upvotes: 3
Views: 4976
Reputation: 2206
func nextChar(str:String) {
if let firstChar = str.unicodeScalars.first {
let nextUnicode = firstChar.value + 1
if let var4 = UnicodeScalar(nextUnicode) {
var nextString = ""
nextString.append(Character(UnicodeScalar(var4)))
print(nextString)
}
}
}
nextChar(str: "A") // B
nextChar(str: "ΞΆ") // Ξ·
nextChar(str: "z") // {
Upvotes: 5
Reputation: 539795
If you think of the Latin capital letters "A" ... "Z" then the following should work:
func nextLetter(_ letter: String) -> String? {
// Check if string is build from exactly one Unicode scalar:
guard let uniCode = UnicodeScalar(letter) else {
return nil
}
switch uniCode {
case "A" ..< "Z":
return String(UnicodeScalar(uniCode.value + 1)!)
default:
return nil
}
}
It returns the next Latin capital letter if there is one,
and nil
otherwise. It works because the Latin capital letters
have consecutive Unicode scalar values.
(Note that UnicodeScalar(uniCode.value + 1)!
cannot fail in that
range.) The guard
statement handles both multi-character
strings and extended grapheme clusters (such as flags "π©πͺ").
You can use
case "A" ..< "Z", "a" ..< "z":
if lowercase letters should be covered as well.
Examples:
nextLetter("B") // C
nextLetter("Z") // nil
nextLetter("β¬") // nil
Upvotes: 9