I have the following code in Swift:
func foo()
{
let name = "Hello World"
if name is String
{
}
else
{
}
}
I get the error: 'is' test is always true
I know it is always true! But why is this an error?
Swift compiles your declaration, through type inference, as this:
let name: String = "Hello World"
if name is String { ...
You can't test the type of a variable against the type it was declared as because that will ALWAYS be true, and that fact is evident at compile time. In this case, you know for sure that name is a String. The static typing of Swift means you should never need to do this test. You can always assume that a variable of type String is a String.
To use is the type of the var must be castable, but not identical to, the type you are comparing it to. So this will compile if name is an ambiguous type that could be String or could be something else entirely. Then the test actually makes sense.
let name: AnyObject = "Hello World"
if name is String {
println("name is a string")
} else {
println("name is NOT a string :(")
}
Some more examples of when you can is and when you can't.
// Good
// AnyObject can be casted to String
let name: AnyObject = "Hello World"
if name is String {}
// Also good
// UInt32 can be casted to Int
let num: UInt32 = 123
if num is Int {}
// error: 'String' is not a subtype of 'Int'
// Int cannot be casted to String, this will NEVER be true
let name: Int = 123
if name is String {}
// error: 'is' test is always true
// String will always be string, this will ALWAYS be true
let name: String = "Hello"
if name is String {}
It's an error because Swift tries its hardest to keep you from doing useless things. Swift figures that since this test is always true, you must have intended to do something else.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With