62

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?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Doug Richardson
  • 10,483
  • 6
  • 51
  • 77

2 Answers2

92

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)
}
Doug Richardson
  • 10,483
  • 6
  • 51
  • 77
  • 11
    Or sometimes `AnyObject?`, depending on how you want to handle nil. – Greg Parker Jun 03 '14 at 02:22
  • From docs:Swift includes a protocol type named AnyObject that represents any kind of object, just as id does in Objective-C. https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/BuildingCocoaApps/InteractingWithObjective-CAPIs.html – Ryan Heitner Jun 03 '14 at 16:51
  • 1
    Or if you are sure it is the button just UIButton instead of anyObject – Binarian Jun 16 '14 at 08: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 Sep 25 '15 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](https://github.com/apple/swift-evolution/blob/master/proposals/0116-id-as-any.md) – marc-medley Feb 15 '17 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

Nilesh Patel
  • 6,318
  • 1
  • 26
  • 40