2

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

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

现在我收到失败消息 Binary Operator '==' cannot be applied to unichar 或 String 类型的操作数。我也尝试过转换字符:

if String(character) == "1" 

不工作...

4

2 回答 2

8

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

if UnicodeScalar(character) == "1" {
    //do this thingy   
}
于 2015-06-06T13:05:45.803 回答
1

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

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

输出:

“这是一个 1”

于 2015-06-06T13:27:26.610 回答