swiftui-notes icon indicating copy to clipboard operation
swiftui-notes copied to clipboard

Shouldn't you use an optional instead of empty array?

Open drumnkyle opened this issue 6 years ago • 5 comments

In the Cascading UI updates including a network request section, you mention making an array even though you expect one value so that you can have an empty one when there is no value. Why wouldn't you use an optional in this case and then compactMap instead? If there is a reason, then I would mention it here.

This is a fantastic resource btw. Thank you very much!

drumnkyle avatar Nov 16 '19 01:11 drumnkyle

I read in the code comments that you started to have some kind of explanation about why you didn't use an optional, but it didn't make sense to me. I read more in the comments below and it was a little more clear, but I still don't understand why the empty array helps for removing things. Is it possible to show how the optional version works and why it was problematic?

drumnkyle avatar Nov 16 '19 01:11 drumnkyle

thanks @drumnkyle - let me see if i can reword that a bit.

the heart of the reason is that optional values (when nil) don’t (or didn’t in my experiment) trigger some of the operators to pass through the pipeline, and in my specific example i wanted to know when the result was “nil” to clear the representing UI element.

heckj avatar Nov 16 '19 17:11 heckj

Ohh I see. That explains it. Did you try maybe utilizing the replaceIfNil so that you knew when it was nil? Idk if that would work well because then you’d have to have another value I guess.

drumnkyle avatar Nov 16 '19 17:11 drumnkyle

I didn't, although I suspect your idea is functional and that I could have - at the time, it seemed just as easy to use an array, with the idea that an empty array meant empty value - rather than cobbling some specific value type or class that could encapsulate the idea that "no response is a valid response" so I could clear up the UI displayed. I certainly don't need a full array (only one element for that use case), but I figured "no-code" was good code ;-)

heckj avatar Nov 17 '19 04:11 heckj

Hmm. That’s true it is less code. Just seems like more clever and brings about questions for someone new coming to it. Definitely an interesting case. Thanks for going back and forth on it. Maybe I’ll mess around with it at some point. I’m still very new to Combine.

drumnkyle avatar Nov 17 '19 05:11 drumnkyle