Add an extension/method to all objects in Swift - 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)

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.

Related

Category Or Extention -- Which one will have precedence

I write awakeFromXib in UILabel category plus Swift UILabel extension.
Now I add one brand new UILabel on ViewController (no outlet created).
awakeFromNib is being called from the category and not from Swift extension.
Please guide which one will have precedence and in what circumstances.
Note: ViewController parent class is written in Swift.
First of all - neither Swift extensions nor Objective-C categories should be used to override non-inherited methods (methods already defined in the class being extended). Apple mentions it in both Swift Developer Guide..:
Extensions can add new functionality to a type, but they can’t override existing functionality.
..And Programming with Objective-C documentations:
If the name of a method declared in a category is the same as a method in the original class, or a method in another category on the same class (or even a superclass), the behavior is undefined as to which method implementation is used at runtime.
If you look for a written "contract", it's emphasised in the quoted text above: if a method is defined in an extensions of a Swift class which itself is a subclass of NSObject (and UILabel is indirect subclass of NSObject) it gets dispatched with messaging mechanism (just like a method defined in an Objective-C category). Thus both methods follow the same Objective-C rules, dispatched the same way, have the same name and the same set of arguments. According to the Apple's own documentation in regards to Objective-C categories it means that the behavior is undefined.
You can probably find empirically some general pattern, but it is not guaranteed to be consistent (can work differently between or even within the same application session) and is a subject to change in future releases.
P.S. It's also double-discouraged to "shadow" Cocoa/Cocoa touch framework classes methods since you may end with suppressing the class own implementation from being called and consequently breaking the dependent logic.

Swift Core Data Usage in Xcode

I am relatively new to Swift Programming and recently tried out Core Data for the first time. However, I am having a hard time understanding several (for me) strange behaviours I am encountering:
I have create all my entities and their attributes in the ".xcdatamodeld" file. Codegen is on "Manual/None". Some of the attributes are marked a non-optional. Still, when I generate the NSManagedObject Subclass files, I still see them as optional in the "...Properties" files, i.e. having a "?" after the type. Why is that?
Somewhat relating/in contrast to the first bullets, the attributes for some entities do not have the "?", although they are marked as optional. When I try to add the "?", I get an error "Property cannot be marked #NSManaged because its type cannot be represented in Objective-C". Why is that?
When I'm creating the NSManagedObject Subclasses and select some subfolder in my project for them to be created in, they are put at the top of the hierarchy tree, regardless.
What happens if I change information in the "...Class"/"...Properties" files generated by Core Data which would conflict with what is in the ".xcdatamodeld" file. What takes precedence? How are they related?
In general I find there is not much detailed descriptions available on Core Data except introductory things. Would anyone know some good resources on that? Website? Youtube Videos? Books?
Answers:
Creating the subclasses manually treates the optionals not accurately. Check any attribute and remove the question mark in the class if it's non-optional in the model.
Scalar Swift optional types (Int?, Double?, Bool?) cannot be represented in Objective-C. I recommend to declare them as non-optional.
Never mind, it has no effect where the classes are located, the main thing is that the file name is black (valid) in the Project Navigator and the target membership is assigned correctly.
in the Codegen Manual / None case you are responsible that the types in the model match the types in the classes otherwise you could get unexpected behavior. Any change in the class must be done also in the model and vice versa. However you can replace suggested ObjC classes like NSSet or NSDate with native Swift types Set<MyClass> or Date without changing the type in the model.

Best Practices: description vs debugDescription

Headline: description called by super.init()
This is a new take on an old question. As a primarily Swift programmer I tend to not use NSObject for class definitions because of the residual side effects of Objective-C. Like if I have a read-only property called length and I then want to create a setter function called setLength, I get warnings about it conflicting with a similar definition from Objective-C. I just discovered the set(var){} setter. If I subclass a Cacoa class like UIDocument, etc. that inherit from NSObject, I have to live with these side effects.
I have a class that uses two other classes in the property definitions, none of them NSObjects. This class has a description computed variable that uses the description computed variables for the other two classes in its composition. All three classes need to conform to the CustomStringConvertable protocol. Ok, everything is good.
At some point this class got upgraded to being a UIDocument and the CustomStringConvertable became redundant and was removed. Everything still works.
Here is what I found out today. I wanted to break at a point in the program where it was printing one of the two properties and as a convenience I set the break point in the description variable for that class, thinking that it should only be called at the point I am interested in, where it is printed out. What I discovered is that the description variable gets called during all the super.init() of the UIDocument sub-class! And there were a few of them. I think composing strings as being relatively expensive but didn't care because they were only used in debug, but with them being called and who knows how they are used in super.init(), I need to change this.
I checked another UIDocument class in the same program that has 200 files associated with it and it is also calling description in super.init().
Does anyone have any input on the Best Practices for using description vs debugDescription?
I'm going to answer my own question as a matter of documentation.
I switched the UIDocuments subclasses to define and use debugDescription. I am debugging some code that loads all the files and does some manipulation and I was able to reduce the load time from 9.8 seconds to 6.8 seconds.
I also went through all the places where the Swift 3 conversion added String(describing:) to the program and found I could change a lot of them to using debugDescription and eliminate the String(describing:) wrapper.
I think the best practice is to only define and use debugDescription and for my non-NSObjects change conformance from CustomStringConvertable to CustomDebugStringConvertable.

Why does adding 'dynamic' fix my bad access issues?

I'm having a strange issue that appeared with iOS 8 Beta 5 (this issue did not occur with previous versions).
I tried to create an empty project and try to replicate the issue, but I'm unable to do so, so I'm not quite sure where the issue lies.
What I'm seeing is that attempting to access methods of a custom NSManagedObject subclass results in a strange EXC_BAD_ACCESS error.
For example:
var titleWithComma: String {
return "\(self.title),"
}
This method, out of many others, causes this issue when called. However, adding a dynamic keyword before it makes the issue go away:
dynamic var titleWithComma: String {
return "\(self.title),"
}
I know I'm not giving enough info, because I honestly don't know how to pinpoint the actual issue, but can anyone explain what is possibly happening, and why adding dynamic might resolve this issue?
From Swift Language Reference (Language Reference > Declarations > Declaration Modifier)
Apply this modifier to any member of a class that can be represented
by Objective-C. When you mark a member declaration with the dynamic
modifier, access to that member is always dynamically dispatched using
the Objective-C runtime. Access to that member is never inlined or
devirtualized by the compiler.
Because declarations marked with the dynamic modifier are dispatched
using the Objective-C runtime, they’re implicitly marked with the objc
attribute.
It means that your property/method can be accessed by Objective-C code or class. Normally it happens when you sub-classing a Swift class of Objective-C base class.
This is from the prerelease Swift / Objective-C interoperability documentation:
Implementing Core Data Managed Object Subclasses
Core Data provides the underlying storage and implementation of properties in subclasses of the NSManagedObject class. Add the #NSManaged attribute before each property definition in your managed object subclass that corresponds to an attribute or relationship in your Core Data model. Like the #dynamic attribute in Objective-C, the #NSManaged attribute informs the Swift compiler that the storage and implementation of a property will be provided at runtime. However, unlike #dynamic, the #NSManaged attribute is available only for Core Data support.
So, because of some of the Objective-C runtime features that Core Data uses under the covers, Swift properties need to be specially annotated.

Why is there no universal base class in Swift?

The documentation says
NOTE
Swift classes do not inherit from a universal base class. Classes you
define without specifying a superclass automatically become base
classes for you to build upon.”
Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks.
It doesn't make much sense to me. There is a reason why Objective-C has a universal base class, and the same reason should apply to Swift, does it? NSObject manages retain/release semantics, a default implementation for isEqual:, hash and description. All this functionality is available in Swift too.
(Objective-C and Swift use the same runtime...)
So, what's up with that? Are Swift classes with no defined superclasses just NSObjects that pose as proper root classes under the hood? Or is the default object-behaviour duplicated for each new root-class? Or have they created another Swift-baseclass? The implementation of retain and release is really complex, because it needs to take multithreading and weak references into account at the same time.
Is there maybe a universal base class in Swift (despite what the documentation says)? It would be really handy, because in Objective-C I can e.g. write extensions that let me coalesce method invocations to the main runloop like [obj.eventually updateCounter] which can be read as "call -updateCounter the next time the main runloop gets in control. If, in the meantime, I call this method again, it should be called only once anyways. With this extension one could implement -[UIView setNeedsDisplay] as [self.eventually display]; This is no longer possible in Swift if there is no universal base class (or maybe it is, who knows?)
There are several object-oriented languages where one can define new root classes, including C++, PHP, and Objective-C, and they work fine, so this is definitely not a special thing.
There is a reason why Objective-C has a universal base class
As Sulthan mentioned, this is not true. There are multiple root classes in Objective-C, and you can define a new root class by simply not specifying a superclass. As Sulthan also mentioned, Cocoa itself has several root classes, NSObject, NSProxy, and Object (the root class of Protocol in ObjC 1.0).
The original Objective-C language was very flexible and someone could in theory come along and create his own root class and create his own framework that is completely different from Foundation, and uses methods completely different from retain, release, alloc, dealloc, etc., and could even implement a completely different way of memory management if he wanted. This flexibility is one of the things so amazing about the bare Objective-C language -- it simply provides a thin layer, all the other things like how objects are created and destroyed, memory management, etc., can all be determined by the user frameworks sitting on top.
However, with Apple's Objective-C 2.0 and modern runtime, more work needed to be done to make your own root class. And with the addition of ARC, in order to use your objects in ARC, you must implement Cocoa's memory management methods like retain and release. Also, to use your objects in Cocoa collections, your class must also implement things like isEqual: and hash.
So in modern Cocoa/Cocoa Touch development, objects generally must at least implement a basic set of methods, which are the methods in the NSObject protocol. All the root classes in Cocoa (NSObject, NSProxy) implement the NSObject protocol.
So, what's up with that? Are Swift classes with no defined
superclasses just NSObjects that pose as proper root classes under the
hood? Or is the default object-behaviour duplicated for each new
root-class? Or have they created another Swift-baseclass?
This is a good question, and you can find out by introspection with the Objective-C runtime. All objects in Swift are, in a sense, also Objective-C objects, in that they can be used with the Objective-C runtime just like objects from Objective-C. Some members of the class (the ones not marked #objc or dynamic) may not be visible to Objective-C, but otherwise all the introspection features of the Objective-C runtime work fully on objects of pure Swift classes. Classes defined in Swift look like any other class to the Objective-C runtime, except the name is mangled.
Using the Objective-C runtime, you can discover that for a class that is a root class in Swift, from the point of view of Objective-C, it actually has a superclass named SwiftObject. And this SwiftObject class implements the methods of the NSObject protocol like retain, release, isEqual:, respondsToSelector:, etc. (though it does not actually conform to the NSObject protocol). This is how you can use pure Swift objects with Cocoa APIs without problem.
From inside Swift itself, however, the compiler does not believe that a Swift root class implements these methods. So if you define a root class Foo, then if you try to call Foo().isKindOfClass(Foo.self), it will not compile it complaining that this method does not exist. But we can still use it with a trick -- recall that the compiler will let us call any Objective-C method (which the compiler has heard of) on a variable of type AnyObject, and the method lookup produces an implicitly-unwrapped optional function that succeeds or fails at runtime. So what we can do is cast to AnyObject, make sure to import Foundation or ObjectiveC (so the declaration is visible to the compiler), we can then call it, and it will work at runtime:
(Foo() as AnyObject).isKindOfClass(Foo.self)
So basically, from the Objective-C point of view, a Swift class either has an existing Objective-C class as root class (if it inherited from an Objective-C class), or has SwiftObject as root class.
This is mainly a design decision, there are languages which have a root class (e.g. Java) and languages which don't (e.g. C++).
Note that in Obj-C a root class is not enforced. You can easily create an object which doesn't inherit from any class. You can also create your own root classes, there are at least 3 in the Apple API (NSObject, NSProxy and deprecated Object).
The reason to have a root class is mostly historical - the root class ensures that all objects have some common interface, some common methods (e.g. isEqualTo:, hash() etc.) which are necessary for collection classes to work.
Once you have generics (or templates in C++), having a root class is not so important any more.
retain and release in NSObject are not important anymore since ARC. With MRC, you were still required to call them. With ARC you never call the methods explicitly and they can be implemented more efficiently behind the scenes.
In Swift, the methods from NSObject have been divided into protocols - Equatable, Hashable, Printable and DebugPrintable. That has the advantage that objects can share interfaces with structs.
However, there is nothing stopping you from inheriting every class from NSObject. The class is still there and it is especially useful if you are dealing with Obj-C APIs. In pure Swift, a root class is not necessary though.
One more note:
Swift classes doesn't run on top of Obj-C; they are not translated into Obj-C behind the scenes. They are just compiled by the same compiler which allows them to interoperate with each other. That's really important to understand. That's why #objc must be sometimes added to provide consistency with Obj-C protocols/classes.