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)
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
- Using Segue Manually
- Text View Placeholder Swift
- Issue testing and using Cocoapods in a Swift project
- @try/@catch doesn't catch exception
- why is there a delay when moving object using UIPanGestureRecognizer
- CFURLCreateStringByAddingPercentEscapes is deprecated in iOS 9, how do I use “stringByAddingPercentEncodingWithAllowedCharacters”
- convert NSData Length from bytes to megs
- Crash when open containing app from today extension
- Autofill Username and Password UIWebView Swift
- Apply rich text format on selected text of UITextView in iOS
- Decrease Space between UICollectionViewCells
- iOS: playing a frame-by-frame greyscale animation in a custom colour
- AVCAPTURE image orientation
- how to return multiple values from a method
- How to present a ViewController with a UIImagePickerController