Add an extension/method to all objects in Swift
In Objective-C, all objects can be treated as type id, and nearly all objects inherit from NSObject. (Blocks don’t, but that’s about the only exception.)
Thus it’s possible to create an Objective-C category that extends ALL Objective-C objects. (ignoring blocks)
In Objective-C, I created an extension to NSObject that uses associated objects to optionally attach a dictionary to any NSObject. That enabled me to implement methods
assocValueForKey: that makes it possible to attach a key/value pair to any NSObject. This is useful in lots of circumstances.
It makes it possible to add stored properties to a category, just for example. You just write a getter/setter that uses the associated value methods to attach a stored object, and away you go.
It also makes it possible to attach values to existing system objects at runtime. You can hang data or blocks of code on buttons, or do whatever you need to do.
I’d like to do the same thing in Swift.
However, Swift does not have a common base class for all objects like Objective-C does.
Any are protcols.
I’m at a loss as to where to “attach” my
assocValueForKey: methods in Swift.
I could create a base class for my extension, but that defeats the point of using an extension. I could make my base object an Objective-C NSObject, but that means all my objects have to be NSObjects, and Swift objects are not NSObjects by default.
(BTW, this question applies to both the Mac OS and iOS platforms)
- An id conforming to the protocol vs Qualify an id with a protocol
- What happens if two ObjC categories override the same method?
- What are the differences between functions and methods in Swift?
- Objective C calling method dynamically with a string
- Implement a pure virtual method in Objective-C
- Why does a function call require the parameter name in Swift?
Solutions Collect From Internet About “Add an extension/method to all objects in Swift”
No. You’ve pretty much answered your own question–Swift objects don’t have a base class, and the only real way to get around it is to inherit from
- Play YouTube videos with MPMoviePlayerController instead of UIWebView
- accessoryButtonTappedForRowWithIndexPath: not getting called.
- NSExceptionDomains xcode 8 not working
- valid provisioning profile matching the application's Identifier could not be found
- Swift: Force show Navigation Bar in Modal
- Xcode: iPhone app codesign error
- Pass variable to custom UITableViewCell from UIViewController
- <unknown>:0: error: unexpected input file:
- UIImagePickerController on iPad with IOS9
- “This app contains an app extension with an illegal bundle identifier” issue
- UIRefreshControl without UITableViewController
- iOS – UIEventTypeRemoteControl events not received
- Is that possible to add a label to the UISlider's thumb image?
- What is the impact of the “Requires full screen” option in Xcode for an iPhone-only app?
- Using existing system sounds in iOS App [swift|