ritsz
June 28, 2020, 9:20am
1
In some chapters of the book there’s lines like this:
if let error = error as NSError?
whereas in Swift I usually see optional binding like this:
if let something = something as? Type
Can someone explain the difference and why we’re using “as Type?” instead of “as? Type”, I don’t get it.
Thank you!
1 Like
@ritsz The first line of code uses as
to typecast error
to NSError?
because you are sure that error
is of type NSError?
in this case.
The second line of code uses as?
to downcast something
to Type
since this definitely fails if something
isn’t of type Type
.
Please do let me know if you have any other questions or issues about the whole thing when you get a chance. Thank you!
ritsz
July 7, 2020, 4:53pm
3
To me it looks weird to use if let
when typecasting to an optional, I’m used to see it for optional binding (to unwrap the optional) instead, but I understand. Thank you.
@ritsz You use if let
in the first case to unwrap error
because it may be nil
since it is of type NSError?
.
You use if let
in the second case to unwrap something
because it is nil
if the downcast to Type
fails.
Please do let me know if you have any other questions or issues about the whole thing when you get a chance. Thank you!
system
Closed
December 12, 2020, 1:20am
5
This topic was automatically closed after 166 days. New replies are no longer allowed.