Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extend all Swift Objects

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?

like image 873
cfischer Avatar asked Sep 04 '14 10:09

cfischer


People also ask

How do you extend multiple classes in Swift?

extension TypeA, TypeB, TypeC, TypeD { func baz() { ... } } This would allow extending multiple Types at once without using a protocol with a default implementation.

Can we extend struct in Swift?

A Swift extension allows you to add functionality to a type, a class, a struct, an enum, or a protocol.

How do I use Swift 5 extension?

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


1 Answers

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.

like image 161
Rob Napier Avatar answered Oct 13 '22 04:10

Rob Napier