Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

xcode

swift

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?

like image 645
Kyle Clegg Avatar asked Nov 29 '22 11:11

Kyle Clegg


1 Answers

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.

like image 195
vacawama Avatar answered Dec 15 '22 05:12

vacawama