12

Is it possible to extend all existing Swift objects as when adding a category over NSObject in Objective C?

According to this article, all Swift objects inherit from the SwiftObject class, but I can't add an extension to it.

Is there any solution to this?

1
  • 3
    That SwiftObject business may be an implementation detail, but Swift classes that don't inherit from another class are by default root classes. Commented Sep 4, 2014 at 11:23

1 Answer 1

11

No. Swift objects do not actually inherit from any root base class. The compiler may insert one as an implementation detail, but the language does not have this.

The solution is a function, and usually a generic function, rather than a method. Something that applies to "every kind of object" isn't really encapsulated. There are very few actions that apply to every conceivable thing in the universe. But functions can map absolutely anything to absolutely anything else, so are a better tool here.


Just as a note, not all objects inherit from NSObject either, and it's not a language requirement. But you're correct that the vast majority do. Take a look at NSProxy for the top of a non-NSObject tree (it implements the NSObject protocol, but does not inherit from the NSObject class). That's why id is not the same thing as NSObject*.


To your question about associated objects, this is built-in:

import Foundation

class Thing { }

let thing = Thing()

var MyKey: Character = "0"

objc_setAssociatedObject(thing, &MyKey, "I'm a value!", objc_AssociationPolicy(OBJC_ASSOCIATION_COPY))

println(objc_getAssociatedObject(thing, &MyKey))

Is this what you were trying to create? Note that objc_setAssociatedObject is also a function, not a method, in ObjC.

Sign up to request clarification or add additional context in comments.

4 Comments

What I was planning to do was to implement something similar to ObjectiveC's associated_object. Any ideas on how to do that with a generic function?
You can use associated objects with Swift. Why would you recreate it? (Edited answer with an example) Or do you mean something else?
@RobNapier: Sometimes people define a category to use associated objects to be able to use them via a normal method API rather than having to use the functions from the runtime.
Sure; I do that all the time to add things to specific classes, but why would you build that on NSObject?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.