Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Use of unresolved identifier" using the new Swift 2.2 syntax for selectors on implicit setter

Tags:

swift

Migrating my code to Swift 2.2, I have a property var activeTextField:UITextfield? and the selector I was using was "setActiveTextField:". This method does not exist explicitly in my swift code.

With the new syntax, #selector(setActiveTextField) doesn't work: Use of unresolved identifier

I know I could use Selector("setActiveTextField:") but I'd loose the benefit of the new swift selectors.

So, what's the new way of doing this?

like image 637
Matthieu Riegler Avatar asked Feb 08 '23 10:02

Matthieu Riegler


2 Answers

The issue here is that you're working with a property, not a method. This has two problems:

  • The ObjC setter/getter method pair for a property is generated at run time.
  • The #selector expression requires a Swift function/method reference.

When Swift compiles your source, it doesn't know that the ObjC -(UITextField*)activeTextField and -(void)setActiveTextField:(UITextField*)field methods will exist, so it can't generate function references for them. Since it can't generate a function reference, it doesn't have something it can use for the #selector expression.

For now, there isn't a way to use #selector to access property getters/setters — using Selector(...) with a string constant is your only option.

(This is actually just a new face on a longstanding known issue... it's the same reason you also can't pass a property getter/setter to something like map or filter. I think I've seen something on http://bugs.swift.org about this, but I'm not finding it at the moment.)

like image 60
rickster Avatar answered May 28 '23 12:05

rickster


In Swift 3, SE-0064 was accepted to solve this problem. Now, you would generate that setter like so:

#selector(setter: activeTextField)
like image 21
Jeff Kelley Avatar answered May 28 '23 13:05

Jeff Kelley