Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert unichar to String?

Tags:

swift

I'm getting a unichar type returned from NSString's instance method characterAtIndex(Int) and I want to compare it with a Swift type String. 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

like image 871
aleclarson Avatar asked Jun 07 '14 08:06

aleclarson


1 Answers

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

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).
  • Character (element of String) has init(_ scalar: UnicodeScalar).

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

like image 177
ishkawa Avatar answered Sep 20 '22 10:09

ishkawa