How do you know which string to provide as a selector for Swift functions?

Patrick Lynch

Sometimes when I am working with selectors in Swift (i.e. the Selector type), the string literal that I provide for the action parameter to methods like targetForAction(_:withSender:) or addTarget(_:action:) doesn't invoke or map to the actual Swift function to which I am expecting.

For example, when an instance of MyResponder as shown below is in the responder chain, it cannot be found when calling targetForAction(_:withSender) using the string showImage:. What is the pattern for knowing what is the proper string literal to provide for different types of Swift function signatures and the options for required and/or omitted argument labels?

import UIKit

class MyResponder: UIResponder {

    func showImage( named filename: String ) {
        print( "Loading image..." )
    }
}

class MyViewController: UIViewController {

    @IBAction func buttonTapped( sender: AnyObject? ) {
        if let responder = self.targetForAction( "showImage:", withSender: self ) as? MyResponder {
            responder.showImage(named: "my_image" )
        }
    }
}
Patrick Lynch

With some trial, error and encouragement from commenters, I managed to figure out the pattern!

The string literal has to follow Objective-C syntax translated from the signature of your Swift function, which is an interesting tidbit that wasn't obvious at first, but makes perfect sense when you consider the purpose things like the @objc attribute. In writing up a better code sample, I seem to have figured out the pattern for the mappings myself.

functionName + (With + First) + : + (second) + : etc.

Where what's in the parenthesis is required only when the argument label is required (i.e. not omitted). And remember to capitalize With and First.

In each of the following examples, myObject will return itself as the target for the provided selector, indicating that the string literal provided as the Selector did in fact map that the Swift function for which it was intended.

import UIKit

class MyObject : UIResponder {
    func someFunction() {}
    func someFunction(param:String) {}
    func someLabeledFunction(param param:String) {}
    func someTwoArgumentFunction(param1:String, param2:String) {}
    func someTwoArgumentNoLabelFunction(param1:String, _ param2:String) {}
    func someHalfLabeledTwoArgumentFunction(param1 param1:String, _ param2:String) {}
    func someCompletelyLabeledTwoArgumentFunction(param1 param1:String, param2:String) {}
}

let myObject = MyObject()
myObject.targetForAction("someFunction", withSender: nil)
myObject.targetForAction("someFunction:", withSender: nil)
myObject.targetForAction("someLabeledFunctionWithParam:", withSender: nil)
myObject.targetForAction("someTwoArgumentFunction:param2:", withSender: nil)
myObject.targetForAction("someTwoArgumentNoLabelFunction::", withSender: nil)
myObject.targetForAction("someHalfLabeledTwoArgumentFunctionWithParam1::", withSender: nil)
myObject.targetForAction("someCompletelyLabeledTwoArgumentFunctionWithParam1:param2:", withSender: nil)

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How do you name the functions in a Swift Protocol?

How do you know which components to import when unit testing?

How do you know which table has returned the data

How are you supposed to know which pyTZ is actually going to do as expected?

In Akka how do you know which request timed out?

How do you know which interface a broadcast message came from?

How do you know which conda channel to install from?

how do you know which items contained in the IN clause that were not found?

How do loss functions know for which model to compute gradients in PyTorch?

How to format a date string if you do not know the format of date input?

transform dataframe: Do you know how group string columns in pyspark?

In Virtual Box, how do you know which NIC is which from the linux command line?

How do you know which Azure App Service instance you are accessing?

In Swift, how do you detect which UIControlEvents triggered the action?

Do you know how to loop this?

how you know which item is an image or button

How to know which functions the package includes?

How do you call a location inside of a list which is a string?

how do you provide deep mock objects?

How do you provide an icon for an action extension?

How do you know which S3 permissions to choose in AWS IAM policies

In a knockout custom binding, how do you know which value is triggering the update?

Hash Tables and Separate Chaining: How do you know which value to return from the bucket's list?

How do CakePHP callback functions know that $q is a Query object and which table to execute the query on?

How do I know which AVX C functions are available on different processor models

PostgreSQL - how do I know which partition I'm in when using window functions?

How do Recursive Functions know which variable to use when called in a math equation?

How do you use perform(#selector(setter:)) to set the value of a property using swift 4?

How to know which segue was used using Swift?