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)

  • Objective-C: my class with static methods “does not implement methodSignatureForSelector: — trouble ahead”
  • Objective C calling method dynamically with a string
  • Method Syntax in Objective C
  • Passing Data between View Controllers
  • Objective c implement method which takes array of arguments
  • How would you define a simple “min” method in obj-c
  • 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 setAssocValue:forKey: and 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. AnyObject and Any are protcols.


    extension AnyObject

    Won’t compile.

    I’m at a loss as to where to “attach” my setAssocValue:forKey: and 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 NSObject.