It is logically sound in its context here, but in general, p is not guaranteed to still be nonânil when the forceâunwrap happens. It may have changed due to another thread, or as a sideâeffect of any of the calls inside the ternary. The map variant is definitively safer to make a habit of.
I don't think there's a possibility for p to be nil. I'd just force unwrap p.
let p = preferences.first(...)!
Even if it's nil, that'd mean that there's no selection. It'd be much better to fade-out the data instead of snapping the box to .zero. Maybe something like this
guard let p = ... else {
return nil
}
Otherwise, what you're using LGMT.
FWIW, p being both local variable and struct is a very strong context. So it must be much more general than this to pose a problem.
Yes, it is fine in that function and that is what I meant by âcontextâ.
I said what I did because the question sounded like it was about which coding pattern is generally better to make a habit of writing. In that case it is significant that if let or map actually establish a strong reference and prevent the value from changing or vanishing before the conditional operation takes place; if x != nil together with x! does not.
I see. I haven't tried it, though technically speaking, it'd be a correct program.
My guess is that the compiler couldn't infer the return type. It would be an Optional of some View, which is also View. Figuring out a way to make that work is probably way outside the scope of this thread.
If it's provably not nil, then you can just force unwrap.