This is never the case, because it is legally impossible. If the timeline is as you suggest, where Apple develops the tech in secret before someone obtains a patent on it, then Apple's research would be prior art to that patent and it would be invalid. So, no, this can't happen.
Ehem... you are confusing two very different things: Whether someone could do this (win) or whether they could sue you. People can sue you for anything. As if a company has never lost a patent lawsuit before. Or as if a company has never had a patent invalidated before.
[doublepost=1510083568][/doublepost]
First to file gets the patent. It was first to invent but it got changed. From memory this was over 10 years ago.
Patents can be invalidated for a number of reasons. Apple has had patents invalidated before. And that is to say nothing about having two similar but different patents (for slightly different methods of doing something similar). Company A can sue Company B for infringement. The court would then have to decide if both companies have valid Patents, and if the company being sued is infringing on the other companys patent.