Use selectors and key paths to interact with dynamic Objective-C APIs.
Overview
Some Objective-C APIs—like target-action—accept method or property names as parameters, then use those names to dynamically call or access the methods or properties. In Swift, you use the #selector
and #key
expressions to represent those method or property names as selectors or key paths, respectively.
Use Selectors to Arrange Calls to Objective-C Methods
In Objective-C, a selector is a type that refers to the name of an Objective-C method. In Swift, Objective-C selectors are represented by the Selector
structure, and you create them using the #selector
expression.
In Swift, you create a selector for an Objective-C method by placing the name of the method within the #selector
expression: #selector(My
. To construct a selector for a property’s Objective-C getter or setter method, prefix the property name using the getter:
or setter:
label, like #selector(getter: My
. The example below shows a selector being used as part of the target-action pattern to call a method in response to the touch
event.
If you need to disambiguate between overloaded functions, use parenthesized expressions along with the as
operator to make the #selector
expression refer unambiguously to a specific overload.
Use Key Paths to Dynamically Access Objective-C Properties
In Objective-C, a key is a string that identifies a specific property of an object. A key path is a string of dot-separated keys that specifies a sequence of object properties to traverse. Keys and key paths are frequently used for key-value coding (KVC), a mechanism for indirectly accessing an object’s attributes and relationships using string identifiers.
Important
Objective-C key paths are distinct from, but related to, key-path expressions in Swift. For information about key-path expressions, see Key-Path Expression in The Swift Programming Language (Swift 4.1).
You use the #key
string expression to create compiler-checked keys and key paths that can be used by KVC methods like value(for
and value(for
. The #key
string expression accepts chained method or property references. It also supports chaining through optional values within a chain, such as #key
. Key paths created using the #key
string expression don’t pass type information about the properties or methods they reference to the APIs that accept key paths.
The example below defines a Person
class, creates two instances of it, and uses several #key
string expressions to access properties and properties of those properties: