Last active
February 28, 2016 23:46
-
-
Save an0/27d0e2c887035b92d96e to your computer and use it in GitHub Desktop.
Optional Type Casting Issues
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This code snippet reveals so many issues:
1/ Playground reports this warning:
But REPL executes the same code successfully:
2/ Playground reports this error:
But as you just saw above,
b is Foo
is true. Why can't we testb is Bar
?3/ Playground reports this warning:
But it is not true. After commenting out the code that triggers the 2nd error above, it changes to this runtime exception:
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:
But do you remember the 2nd error above? It does't allow us to test
if b is Bar
. Whycase is Bar
is allowed?