我想在运行时检查对象是否是可选的String类型。 为什么以下不能在我的命令行项目中编译?
var p:String?
if p is String {
println("p is string")
}
else {
println("p is not string")
}
构建错误:
Bitcast requires both operands to be pointer or neither
%81 = bitcast i8* %80 to %SS, !dbg !131
Invalid operand types for ICmp instruction
%82 = icmp ne %SS %81, null, !dbg !131
PHI nodes must have at least one entry. If the block is dead, the PHI should be removed!
%85 = phi i64
PHI node operands are not the same type as the result!
%84 = phi i8* [ %81, %73 ]
LLVM ERROR: Broken function found, compilation aborted!
Command /Applications/Xcode6-Beta2.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swift failed with exit code 1
答案 0 :(得分:3)
首先必须为其分配值。像这样:
var p : Any?
p = "String"
if p is String {
println("p is a String")
} else {
println("p is something else")
}
答案 1 :(得分:2)
首先,即使XCode不正确,XCode也不应该崩溃,因此我会向Apple提交错误报告。
但是你的代码确实没有意义。您将p设置为可选字符串,然后询问它是否为字符串。一个可选的String可以包含一个String或者nil,所以你最好只检查它是不是nil:
var p: String?
if p {
println("p is string")
}
else {
println("p is not string")
}