将unichar转换为String?

时间:2014-06-07 08:16:39

标签: swift

我从unichar的实例方法NSString返回characterAtIndex(Int)类型,我想将其与Swift类型String进行比较。有一个简单的方法吗?

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

由于

2 个答案:

答案 0 :(得分:9)

使用UnicodeScalar将unichar转换为String或Character(String的元素)。

var str = "#ffffff"
var unichar = (str as NSString).characterAtIndex(0)
var unicharString = Character(UnicodeScalar(unichar))
var containsHash = unicharString == "#"
  • unichar是UInt16(typealias unichar = UInt16)的别名。
  • UnicodeScalar有init(_ v: UInt16)
  • 字符(字符串元素)有init(_ scalar: UnicodeScalar)

注意:字符串也有init(count: Int, repeatedValue c: UnicodeScalar),但这不适合这种情况。

答案 1 :(得分:2)

var str:String = "#ffffff"
var unichar = str[str.startIndex]
var unicharString = "\(unichar)"
var containsHash = unicharString == "#"