对单字符和字符串使用二进制运算符



我正在尝试使用二进制运算符来比较两个值:

character = (xxx as NSString).characterAtIndex(2)
if character == "1" {
    //do this thingy   
}

现在我收到失败消息二进制操作符'=='不能应用于类型为unichar或String的操作数。我还尝试转换字符:

if String(character) == "1" 

由于unichar是别名为16位整数的类型,因此需要将其"包装"在UnicodeScalar函数中进行比较:

if UnicodeScalar(character) == "1" {
    //do this thingy   
}

这是另一种方法。改变从String获得character的方式:

let xxx = "321"
let character = xxx[advance(xxx.startIndex, 2)]
if (character == "1") {
    println("it is a 1")
}
输出:

"it is a 1"

最新更新