Swift: if reservation is allowed
I just joined a project with a lot of existing code. The previous programmer may have been unfamiliar with Swift or started developing early in the Swift language. They seem to have used the operator in if let
an odd way. They seemed to want to use the statement like if is let
. Before I edit the code, I would like to know if there is any valid use for this:
// In JSON parser
if value is String, let string = value as? String {
document.createdBy = string
}
First check if the type value String
seems overkill to me. Does Swift check this in the let string = value as? String
assertion part ?
Question
Why do you need to double check this? Or could there be a reason for this?
source to share
You are right, this is redundant. If value
it is not a string, it value as? String
will return nil
, and conditional binding will fail.
To check the type and not use the resulting result:
if value is String {
// Do something that doesn't require `value` as a string
}
To check the type and use the result:
if let value = value as? String { // The new name can shadow the old name
document.createdBy = value
}
Doing both doesn't make sense.
source to share