Matthieu Riegler Matthieu Riegler - 1 year ago 68
Swift Question

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

Migrating my code to Swift 2.2, I have a property

var activeTextField:UITextfield?
and the selector I was using was
. This method does not exist explicitly in my swift code.

With the new syntax,
doesn't work:
Use of unresolved identifier

I know I could use
but I'd loose the benefit of the new swift selectors.

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

Answer Source

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 about this, but I'm not finding it at the moment.)