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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 05:25:48  来源:igfitidea点击:

Conditional downcast from 'String' to 'String' always succeeds - Swift Error

xcodeswift

提问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 zipCodecan 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 zipCodeis set, then codewill be a constant of type Stringthat you can use to safely access the contents of zipCodeinside the ifblock.

用于检查可选变量是否有值,或者它是否仍然未设置 ( nil)。如果zipCode设置,code则将是一个类型的常量String,您可以使用它来安全地访问块zipCode内部的内容if