Swift sometimes calls wrong method Swift sometimes calls wrong method ios ios

Swift sometimes calls wrong method

This just happened on my team, using Swift 2.2. It's really incredibly strange. It's not a threading issue or an async problem, it was a very cut & dry use case. We called one instance method and another one above it got called. I deleted the method that was getting called, and then the one above THAT got called instead. Then I moved the method I was actually calling to a different location in the file, and it looked like multiple properties were getting called.

This is disturbing and worrisome, as now you feel you can't trust your code to run properly.

But we did "solve" it. We moved the method up to the code that was actually getting triggered, and after a little trial & error the right method got called. Not yet sure if this will manifest itself for other methods.

It'd be nice to be able to provide a simple project where this is happening, but it seems highly unlikely that it's possible, and I can't share a snap shot of my code base with Apple. It must be a perfect storm of something to cause a bug with Swift's run time.

I had a similar issue, I think. Couldn't see that the wrong function was being called, but breakpoints on the function that was being called were never hit, and I couldn't step into the function from where it was being called. I added a new function (I called it wtf) with the same parameter list and implementation, and that one worked as expected, so it must have been a weird linking issue in the Swift compiler.

Update: super-cleaning appeared to work (see below), but it doesn't. Looks like I'm leaving my wtf function in.

After super-cleaning the project, it looks like everything's working as expected again:

  • clean (cmd + shift + k)
  • clean build dir (cmd + opt + shift + k)
  • quit XCode
  • delete derived data (rm -rf ~/Library/Developer/Xcode/DerivedData/*)

FYI, in my case, the function I call is in a generic base class, called from a generic subclass, triggered by a specialized sub-sub-class. As we all know, the generics are still very buggy in the Swift compiler, so that's probably why I encountered this.

Do you have multiple threads running? Maybe a network thread?

I thought I had this issue too but then it turned out my one thread was doing something and because the other thread crashed it stopped the other thread at a random point. I only noticed this thread so it seemed like it crashed at a random @IBAction function.