r/iOSProgramming • u/ThePantsThief NSModerator • Apr 16 '21
Meme Looking at you, Codable and synthesized inits
3
u/wiencheck Apr 17 '21
That’s really frustrating, can someone explain why some code cannot be synthesized fo classes? I asked about it in the past but no one replied
2
u/ThePantsThief NSModerator Apr 17 '21
It's not that it can't be done, it's that they never took the time to decide how it should be done. This is a feature that was a proposal for structs. There has not been a similar proposal (with implementation) for classes yet, AFAIK.
3
u/fartsniffersalliance Apr 17 '21
Huh, I’d never noticed Codable couldn’t be applied to classes because i’ve never had a case where i’ve needed to. What are the use cases for this?
2
u/ThePantsThief NSModerator Apr 17 '21
It can be applied to classes, it's just a bitch to use. It doesn't support synthesizing the init on anything but root classes I believe, or something very close to that.
Reddit's API is a good example of when you might want to use classes because the model uses inheritance. Their model has an inheritance hierarchy like so: thing, created, voteable, post/comment, etc. Thing has an ID and type, created has a date, voteable has a score and can be voted on.
For example, a user object inherits from "created" but not voteable, but posts and comments are both voteables.
You could probably also do this with protocols, but this is just an example of something that was made easy in Objc and is now really hard in Swift with Codable.
1
u/Xaxxus Apr 17 '21
You can use codable on classes.
It’s not that hard either if you have ever implemented a custom decoding/encoding init.
For subclasss in your decode/encode you have to call super.init(from: decoder) and super.encode methods.
It’s just tedious on large classes. Especially if they contain other classes that you also want to decode.
2
u/ThePantsThief NSModerator Apr 17 '21
It’s not that hard either if you have ever implemented a custom decoding/encoding init.
This is something that should be avoided at all costs. Implementing any Codable init is hell, and every time you have to do it just means Codable failed you.
3
u/Xaxxus Apr 17 '21
I wouldn’t say codable has failed. Codable is nothing more than a protocol. Protocols need to be implemented.
The code synthesis is merely a convenience feature. And You can only assume so much about what the best “default behavior” is when synthesizing code.
A good example of this is encoding explicit null values into json. The default behavior is to omit null entirely.
I almost always have to build my own encoder/coding keys for places where I need an explicit null value in my json.
2
u/ThePantsThief NSModerator Apr 17 '21
You missed the point of this post then
A good example of this is encoding explicit null values into json. The default behavior is to omit null entirely.
almost always have to build my own encoder/coding keys for places where I need an explicit null value in my json.
Another failure by Codable. It should be flexible enough to handle 90% of use cases without the need for a hand written initializer. It's not even a difficult problem, they just didn't even try
1
u/OneTinker Apr 17 '21
I've used structs extensively in Golang and C; however, when it comes to Swift, I feel like I haven't completely utilized structs to their optimal nature. I still use classes for majority of my codebase and the only times I use structs is to store a context of simple data primitives or other struct references. Do you have any good resources/articles to highlight the use of structs in a more progressive fashion?
2
u/ThePantsThief NSModerator Apr 17 '21
Someone in the comments here linked Apple's own documentation somewhere. Don't think there's anything wrong with the way you do it now though FWIW
23
u/strauvius Apr 17 '21
Yeah, but then your stuck passing by value instead of by reference.
17
u/AllNewTypeFace Apr 17 '21
The only time passing by reference is preferable is for objects referring to unique resources, such as views, database handles and such.
In the old days, passing by reference was more efficient than passing by value because it’s one pointer rather than an entire data structure, but this is largely a nonissue because (a) the Swift compiler is sufficiently smart to eliminate most redundant copies, internally implementing your value types with copy-on-write semantics (i.e., in the compiled code, until either copy is subsequently modified, they are handled as a reference), and (b) CPUs and cache memory are sufficiently fast that, in the cases where a copy occurs, the performance hit is negligible. Passing by value also guarantees that the value passed will not change, in the way that a struct at the end of a pointer might. So things like decoded JSON records, data entities and such can and should be value types.
5
u/ThePantsThief NSModerator Apr 17 '21
Or when you need a singleton
2
u/AllNewTypeFace Apr 17 '21
If you specifically care about something being a singleton, it’s generally because it represents or contains a unique resource
1
u/ThePantsThief NSModerator Apr 17 '21
I have seen someone try to do that using static struct vars and funcs. Just had to throw it out there. But yeah.
60
u/unpopularOpinions776 Apr 17 '21
Yeah, but then your stuck passing by value instead of by reference.
sometimes you want that
you're
25
Apr 17 '21
[removed] — view removed comment
10
u/skytzx Apr 17 '21
Value types should almost always be preferred over reference types. The speed difference is pretty significant in performance-sensitive code.
There's a WWDC video that goes really in depth on this topic.
40
u/ThePantsThief NSModerator Apr 17 '21
That's not true in the slightest. Did you know that when you have a struct with lots of reference type members (strings and arrays count) that every time you copy the struct, the compiler has to retain each one of them?
Compare this to when you use a class. Every new reference to the object is only one retain.
Classes and structs are both good for different things. There is no silver bullet.
9
u/skytzx Apr 17 '21 edited Apr 17 '21
Yes, I agree there is no silver bullet, which is why I say structs should almost always be preferred over reference types.
Apple's general recommendation is to use structs by default, and switch to classes for ObjC interoperability and in instances where reference semantics are explicitly needed.
Performance-wise, the Swift compiler will automatically omit extraneous retain/releases if it's able to determine they are unneeded. In instances where the lifetime of a struct's value can be determined, the retain/releases of reference type members may be omitted entirely. In a reference type, it cannot be proven easily.
Ideally, avoiding heap allocations altogether would give you the most performant result.
12
u/ThePantsThief NSModerator Apr 17 '21 edited Apr 17 '21
It's funny you should mention the docs; they used to recommend the opposite. That's from the Swift 3.1 handbook. I think this is a much more unbiased take personally, but it's all subjective.
Anyway all of those same optimizations apply to reference types too
9
u/wiencheck Apr 17 '21
I’m saving this for future...reference
9
5
2
u/faja10 Apr 17 '21
Correct me If I am wrong, but doesn’t some recent compiler/Swift release introduce “smart” structs. Maybe I am mistaking it for something but iirc it was supposed to work like this:
u pass structure that lets say has data of x Bytes
new struct is not directly copied
only when u use fe property name, that property is copied and assigned
1
u/ThePantsThief NSModerator Apr 17 '21
Yes probably. I'm referring to worst case scenarios where such optimization is not possible
10
u/javaHoosier Apr 17 '21
I appreciate that you said almost. There is also a WWDC that mentions why reference types were chosen for RealityKit. It’s a good watch.
4
u/gray_goose Apr 17 '21
Would you be able to link me to the WWDC video? I couldn’t find it.
10
1
u/kpolleck Apr 19 '21
What I feel like this and so many other trends in programming are suggesting is "Programmers don't need to understand the layers (hardware, memory, registers, ALUs, etc.) underneath anymore."
It's probably true, but us older programmers mostly won't admit it. It's like the engine of my car. Decades ago, I could have opened the hood and understood everything that was in there any how it worked...and how it made the car go. Now, I just get into the drivers seat and push down the accelerator and hope it all works. And if it doesn't, I call someone.
9
u/[deleted] Apr 17 '21
This but enums instead of classes. Enums are such an integral part of Swift but they’re neglected so much!