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?
2 Answers
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)
}
-
11Or 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
-
1Or if you are sure it is the button just UIButton instead of anyObject– BinarianCommented 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. Commented Sep 25, 2015 at 15:05
-
1As of Swift 3, Objective-C interfaces that use
id
and untyped collections will be imported into Swift as taking theAny
type instead ofAnyObject
. SE-0116 Commented Feb 15, 2017 at 20:40
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