Hi guys what's the most concise way to write this ...
# announcements
j
Hi guys what's the most concise way to write this Swift code in Kotlin?
Copy code
guard let type = model.type, let value = model.value, value != 5 else {
            return
        }
v
Maybe you should exlain what the code does. I for example have no idea about swift
j
guard let type = model.type
defines a new immutable variable called type if
model.type
is not null - if it is then the
else
block gets executed. Basically any statement separated by comma (acts as &&) after guard that is null or false will execute the
else
block.
If no guard statements are null or false then it will skip the else block.
v
I would probably simply do
Copy code
val type = model.type
val value = model.value
if (type == null || value == null || value != 5) {
    return
}
But that might not be the most concise way
👍 1
j
I guess that would be the way. I guess the difference is that in the guard statement, you can define multiple variables in a one-liner at the same time guarding from null values.
g
you can use early return
Copy code
val type = model.type ?: return
val value = model.value ?: return
for this particular case it probably just should be:
Copy code
val type = model.type ?: return
val value = model.value.takeIf { it != 5 } ?: return
👍 1