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?
extension TypeA, TypeB, TypeC, TypeD { func baz() { ... } } This would allow extending multiple Types at once without using a protocol with a default implementation.
A Swift extension allows you to add functionality to a type, a class, a struct, an enum, or a protocol.
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. }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With