Skip to content

Instantly share code, notes, and snippets.

@an0
Last active February 28, 2016 23:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save an0/27d0e2c887035b92d96e to your computer and use it in GitHub Desktop.
Save an0/27d0e2c887035b92d96e to your computer and use it in GitHub Desktop.
Optional Type Casting Issues
class Foo {
}
class Bar: Foo {
}
//let b: Bar? = nil
let b: Bar? = Bar()
let f: Foo? = b
if b is Foo {
print("Foo")
}
if b is Foo? {
print("Foo?")
}
if b is Bar {
print("Bar")
}
if b is Bar? {
print("Bar?")
}
switch b {
case is Foo:
print("Foo")
case is Foo?:
print("Foo?")
case is Bar:
print("Bar")
case is Bar?:
print("Bar?")
default:
break
}
@an0
Copy link
Author

an0 commented Jun 16, 2015

This code snippet reveals so many issues:

1/ Playground reports this warning:

13:6: warning: cast from 'Bar?' to unrelated type 'Foo' always fails```
if b is Foo {
~ ^ ~~~

But REPL executes the same code successfully:

14> if b is Foo {
15. print("Foo")
16. }
Foo

2/ Playground reports this error:

21:6: error: downcast from 'Bar?' to 'Bar' only unwraps optionals; did you mean to use '!'?
if b is Bar {
~ ^ ~~~

But as you just saw above, b is Foo is true. Why can't we test b is Bar?

3/ Playground reports this warning:

17:6: warning: 'is' test is always true
if b is Foo? {
^

But it is not true. After commenting out the code that triggers the 2nd error above, it changes to this runtime exception:

Could not cast value of type 'Swift.Optional' (0x1125ad238) to 'Swift.Optional' (0x1125ad448).

Why can't? Why line 11( let f: Foo? = b) can?

4/ After commenting out the code that triggers the runtime exception above, all the playground warnings go away.

5/ After commenting out the first 2 cases in switch, the 3rd case evaluates to true:

case is Bar:
    print("Bar")

But do you remember the 2nd error above? It does't allow us to test if b is Bar. Why case is Bar is allowed?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment