xcode 从“字符串”到“字符串”的条件向下转换总是成功 - Swift 错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25465321/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Conditional downcast from 'String' to 'String' always succeeds - Swift Error
提问by Kyle Clegg
I'm trying to essentially do an valid check on a String in Swift, however I'm getting an error Conditional downcast from 'String' to 'String' always succeeds
.
我试图对 Swift 中的 String 进行本质上的有效检查,但是我收到了一个错误Conditional downcast from 'String' to 'String' always succeeds
。
zipCode is created:
创建邮政编码:
var zipCode = String()
Checking for a valid string at a later time:
稍后检查有效字符串:
if let code = zipCode as? String {
println("valid")
}
Can someone help me understand what I'm doing wrong?
有人可以帮助我了解我做错了什么吗?
回答by vacawama
If zipCode
can be "unset", then you need to declare it as an optional:
如果zipCode
可以“未设置”,则需要将其声明为可选:
var zipCode: String?
This syntax (which is known as optional binding):
此语法(称为可选绑定):
if let code = zipCode {
print("valid")
// use code here
}
is used for checking if an optional variable has a value, or if it is still unset (nil
). If zipCode
is set, then code
will be a constant of type String
that you can use to safely access the contents of zipCode
inside the if
block.
用于检查可选变量是否有值,或者它是否仍然未设置 ( nil
)。如果zipCode
设置,code
则将是一个类型的常量String
,您可以使用它来安全地访问块zipCode
内部的内容if
。