Swift Struct and Class

  • content
  • comment
  • relevant

Similarities

  • They can define attributes to store values, or they can define functions
  • They can define subscripts to provide access to values subscript syntax (Subscript Syntax)
  • They can define initializers to set their initial state, using init()
  • Extensions in Swift Explained

difference

Class supports some functions not available in the structure

  • Class can inherit from another class, just like creating its own view controller subclass from
  • Class can be de initialized, that is, you can call a function before the class is destroyed
  • Class is a reference type( Reference Type ), structure is value type

When to use structure

  • Simple data type
  • In a multithreaded environment
  • When most properties of the structure are also value types

When to use classes

If you need specific properties of a class, we recommend that you use a class. As mentioned earlier, classes have some additional features that are not available in the structure:

  • It can inherit from another class, which is impossible to do with structure
  • Classes can be initialized, that is, they can implement a deinit Function, you can make one or more references to the same class (that is, the class is a reference type)
  • Class has built-in concepts identity  Identity, you can check whether two references (variables, constants, attributes, etc.) refer to the same object

Note here that if you want to interoperate between Swift and Objective-C, you need to use classes. If you need Objective-C interoperability, you need to use classes. For example, if you want to use @ objc and dynamic in the Realm data model, the model must be a class.

Next to reference and value types, inheritance is the most important difference between classes and structures. Using classes, you can clearly define parent-child connections between subclasses and superclasses.

In conclusion, if you need features that only classes can provide: inheritance, identity, Objective-C interoperability, and the scenario where copying values is meaningless, then it is wise to use classes.

Partially quoted from https://learnappmaking.com/struct-vs-class-swift-how-to/

comment

zero Comments

Post reply

Your email address will not be disclosed. Required items have been used * tagging