Are Golang and Swift worth the effort

It's nice to see that the old Objective-C drivers are so excited about Swift's fresh syntax structure and new way of thinking. As developers, we should always strive to expand our capabilities and be ready to change our mindset when new paradigms emerge.

A similar example is dealing with data structures, immutability, and trying to use constants. This is a good suggestion and should be adopted. Another example is the conversion of our data model to struct. That sounds very nice, but in actual use, using Struct in full instead of Class (class) developers still poses a lot of difficulties.

Don't get me wrong, there are great benefits to using Struct as a data model. However, this is not a perfect solution. In this article I am going to explain in detail the problems that arise when converting the data model from Class to Struct.

Objective-C

If your project code is a mixed development of Swift and Objective-C, you will find that Swift's structure cannot be called in Objective-C code. Because to call Swift code in Objective-C the object must inherit from NSObject.

Struct is not a good friend of Objective-C.

inherit

Inheritance is one of the four pillars of object-oriented programming that is deeply embedded in the way we think. Why do we write certain code repeatedly when we can use inheritance? I want to make my data model inheritable. This saves me from repeating the JSON parsing code to share an abstract class, which keeps my model consistent.

Struct cannot inherit each other.

NSUserDefaults

I dare agree that everyone will feel guilty if they ever put data in NSUserDefaults. This way of thinking is normal because not everyone enjoys working with CoreData, especially when only a few objects are stored. This is technically feasible, but if you want to use struct to achieve this, there are still a few pitfalls to overcome. So you can better implement it with Class.

Struct cannot be serialized to an NSData object.

Advantages of struct

I don't want you to think that I don't like Struct because the structure hurts my feelings. There are many advantages to using Struct instead of Class as a data model. The value type is very beneficial:

  • security

  • R.A.M.

  • speed

  • Copy

  • Thread safe

finally

There are probably that many. I've already pointed out the shortcomings of Struct and listed some of the advantages of Struct so that you can determine whether to use the Struct type as a data model.

However, you can use both together. In my own project, if the model is small and doesn't need to be inherited, stored in NSUserDefault, or used in Objective-C, I would use Struct.

Submitted from: https: //blog.csdn.net/andy_jiangbin/article/details/77837723