63

I'm trying to use an @IBAction to tie up a button click event to a Swift method. In Objective-C the parameter type of the IBAction is id. What is the equivalent of id in Swift?

0

2 Answers 2

93

Swift 3

Any, if you know the sender is never nil.

@IBAction func buttonClicked(sender : Any) {
    println("Button was clicked", sender)
}

Any?, if the sender could be nil.

@IBAction func buttonClicked(sender : Any?) {
    println("Button was clicked", sender)
}

Swift 2

AnyObject, if you know the sender is never nil.

@IBAction func buttonClicked(sender : AnyObject) {
    println("Button was clicked", sender)
}

AnyObject?, if the sender could be nil.

@IBAction func buttonClicked(sender : AnyObject?) {
    println("Button was clicked", sender)
}
5
  • 11
    Or sometimes AnyObject?, depending on how you want to handle nil. Commented Jun 3, 2014 at 2:22
  • From docs:Swift includes a protocol type named AnyObject that represents any kind of object, just as id does in Objective-C. developer.apple.com/library/prerelease/ios/documentation/Swift/… Commented Jun 3, 2014 at 16:51
  • 1
    Or if you are sure it is the button just UIButton instead of anyObject
    – Binarian
    Commented Jun 16, 2014 at 8:20
  • AnyObject? if you think that nil might be called (quite often people call IBAction functions from code, without a sender), MyClass or MyClass? if you know that the sender is of no other class than MyClass.
    – gnasher729
    Commented Sep 25, 2015 at 15:05
  • 1
    As of Swift 3, Objective-C interfaces that use id and untyped collections will be imported into Swift as taking the Any type instead of AnyObject. SE-0116 Commented Feb 15, 2017 at 20:40
0

AnyObject

Other mapping type,

Remap certain Objective-C core types to their alternatives in Swift, like NSString to String

Remap certain Objective-C concepts to matching concepts in Swift, like pointers to optionals

Not the answer you're looking for? Browse other questions tagged or ask your own question.