简体   繁体   中英

Creating a new character from a string in Swift

This is a bit of a strange question. Would it be possible to create a new character in Swift from a string. Let's say that "aa" would be recognized as a separate character from "a" . The same way "\\n" or "\\t" are recognized as single characters even though strictly speaking they are made up of two other characters and when you iterate over a string containing them they will appear as single characters. Even if the solution to this is janky or weird it would save me a lot of time in what I'm doing.

In swift, you can convert string all characters into the set of characters like that and again into string:

let stringData : String = "aa"
var charactersSet = Set(stringData)// ["a"]

let finalResult = String(charactersSet)
/// output = "a"

Every instance of Swift's Character type represents a single extended grapheme cluster. An extended grapheme cluster is a sequence of one or more Unicode scalars that (when combined) produce a single human-readable character.

Source: Strings and Characters .

The issues involved in determining and tailoring grapheme cluster boundaries are covered in detail in Unicode Standard Annex #29 , which gives a number of examples and some algorithms.

Source: Characters and Grapheme Clusters .

So the answer is “no.” You cannot change what Swift considers to be a Character , that is defined by the Unicode standard and compiled into the Swift runtime library.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM