6

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.

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?

1
  • zipCode is a kind of String in every moment, why do you want to downcast it to String, if you already know it is a String? the compiler has been just intelligent enough to warn you not to do such pointless task. if you want to work optional, that would make sense, but your OP has not mentioned anything about any optionals. Commented Aug 23, 2014 at 19:06

1 Answer 1

23

If zipCode can be "unset", then you need to declare it as an optional:

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Ah okay, I was mixing the syntax for an Optional and a string literal. Thanks.
String! is an implicitly unwrapped optional, you probably meant String? ? - And the conditional cast as? String it not necessary here and causes a compiler error if the variable is known to be a (optional) string.
Thanks @Martin R for keeping me honest.
@MartinR: well an implicitly-unwrapped "optional" is still a kind of optional
@newacct: Sure, I just found the first version of the answer a bit unclear.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.