Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add an extension/method to all objects in Swift

Tags:

methods

oop

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 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.

Thus,

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)

like image 204
Duncan C Avatar asked May 11 '15 19:05

Duncan C


People also ask

Where do I put extensions in Swift?

Creating an extension in Swift When creating an extension, you add the word extension before the name. extension SomeNamedType { // Extending SomeNamedType, and adding new // functionality to it. }

How do I use an extension class in Swift?

In Swift, we can add new functionality to existing types. We can achieve this using an extension. Here, we have created an extension of the Temperature class using the extension keyword. Now, inside the extension, we can add new functionality to Temperature .

Can you add a stored property to a type by using an extension how or why not?

Yeah. Extensions cannot contain stored properties. If you need to add a property to a native component, you must create your own button inheriting from UIButton. In my opinion, creating your own button using a UIButton inheritance is the best way to resolve this situation.


1 Answers

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.

like image 156
MLQ Avatar answered Oct 29 '22 17:10

MLQ