Selectors With Parameters in Swift 2.2
I went back today and recompiled all my latest Swift projects – Euchre, CloudKitPOC, Suntracker, Solitaire – to see how much Swift 2.2 would break them. The only thing that I got warnings about (I’m a 0 warnings dev) was about changing from string selectors to using the #selector() syntax. They were all warnings but I had problems fixing one of them. The “Fix-it” solution ended up being another warning.
In Solitaire I have a GameController and a GameViewController. The GameViewController is strictly UI only. There is no game logic what-so-ever in it. All of that is contained in the GameController. I also created a PlayingCardImageView subclass of UIImageView to handle all the interaction with the playing cards. For instance, tapping a playing card will execute any plays that card can make in the game.
When implementing this, I had to decide if I wanted pass the GameController into every PlayingCardImageView or have the target and selector of the UITapGestureRecognizer refer back to the GameViewController. I opted for the later. I only wanted one class to be responsible for passing user interactions back to the GameController.
My code in the PlayingCardImageView for 2.1 was:
let tapGestureRecognizer = UITapGestureRecognizer(target: gameViewController, action: "cardTapped:")
The “Fix-it” solution:
which then lead to…
Hopefully the first thing you’re thinking as a seasoned Xcode user is “Never use Fix-it!!” and you’d be right. Unless you understand what Fix-it is actually doing its much better to dig into the problem yourself and figure out what the fix should be.
The proper solution in Swift 2.2 for this is:
let tapGestureRecognizer =
UITapGestureRecognizer(target: gameViewController, action: #selector(gameViewController.cardTapped(_:)))
It wasn’t the most obvious syntax to arrive at but at least I know now.
BTW – here’s a great rundown of Swift 2.2 changes. I’m looking forward to trying out tuple comparisons – particularly with my NSOperation operationResult tuples in unit tests.
I want to point out that I figured it out quite easily with Xcode code completion. I don’t want this post to sound like a dump on the Xcode team. Xcode gets better and better with every release! I bet its just a miss in the Fix-it logic.