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?

Kyle Clegg
  • 38,547
  • 26
  • 130
  • 141
  • `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. – holex Aug 23 '14 at 19:06

1 Answers1

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.

vacawama
  • 150,663
  • 30
  • 266
  • 294