Convert unichar to String?

I get the unichar type returned from the instance method of NSString characterAtIndex(Int) , and I want to compare it with the Swift String type. Is there an easy way to do this?

 var str = "#ffffff" var unichar = (str as NSString).characterAtIndex(0) var unicharString = // Perform magic var containsHash = unicharString == "#" // Should return `true` 

thanks

+6
source share
2 answers
 var str:String = "#ffffff" var unichar = str[str.startIndex] var unicharString = "\(unichar)" var containsHash = unicharString == "#" 
+2
source

Use UnicodeScalar to convert unichar to String or Character (String element).

 var str = "#ffffff" var unichar = (str as NSString).characterAtIndex(0) var unicharString = Character(UnicodeScalar(unichar)) var containsHash = unicharString == "#" 
  • unichar is an alias of UInt16 ( typealias unichar = UInt16 ).
  • UnicodeScalar has init(_ v: UInt16) .
  • A character (String element) has init(_ scalar: UnicodeScalar) .

Note. The line also has init(count: Int, repeatedValue c: UnicodeScalar) , but this is not suitable for this case.

+8
source

Source: https://habr.com/ru/post/970498/


All Articles