I was asked What is Struct and Class? Could you explain it?
It’s the most common interview question.
I summarized the differences between classes and structure when to use it.
Struct versus Class
Structure and Enum are value types.
-
It is copied when it’s assigned to a variable or constant, or it’s passed to a function.
Classes are reference types.
-
Reference types are not copied when they’re assigned to a variable or constant or when they’re passed to a function. Rather than a copy, a reference to the same existing instance is used.
Structure and Class both can
-
define properties to store values
-
define methods to provide functionality
-
define subscripts to provide access to their values using subscript syntax
-
define initializers to set up their initial state
-
be extended to expand their functionality beyond a default implementation
-
conform to protocols to provide standard functionality of a certain kind
-
Include computed properties.
Classes have additional capabilities that structures don’t have.
-
Inheritance enables one Class to inherit the characteristics of another.
-
Typecasting enables you to check and interpret the type of a class instance at runtime.
-
Deinitializers enable an instance of a class to free up any resources it has assigned.
-
Reference counting allows more than one reference to a class instance.
-
Identity operators to check whether two constants or variables refer to the same single instance.
-
Identical to (===)
-
Not identical to (!==)
-
The structure has additional capabilities that classes don’t have.
-
Memberwise initializers
-
You can use it to initialize the member properties of the new structure instance.
-
Choosing between Structures and Classes
Decide how to store data and model behavior.
When designing a type, we have to think about whether ownership of a particular instance of this type “has to be shared among different parts of our program, or if multiple instances can be used interchangeably as long as they represent the same value. To share ownership of a particular instance, we have to use a class. Otherwise, we can use a struct.
Chris Eidhof. “Advanced Swift.”
Apple’s guide
-
Use structures by default
-
Use structures along with protocols to adopt behavior by sharing implementations.
-
Use classes when you need Objective-C interoperability
-
Use classes when you need to control the identity of the data you’re modeling
Choose Structures
-
It makes it easier to reason about a portion of your code without needing to consider the whole state of your app. Because structures are valued types-unlike classes-local changes to a structure aren’t visible to the rest of your app unless you intentionally communicate those changes as part of the flow of your app.
-
when you don’t control identity
-
Use structure when you’re modeling data that contains information about an entity with an identity that you don’t control.
-
Local changes to model types like PenPalRecord are useful. For example, an app might recommend multiple different penpals in response to user feedback. Because the PenPalRecord structure doesn’t control the identity of the underlying database records, there’s no risk that the changes made to local PenPalRecord instances accidentally change values in the database.
-
If another part of the app changes my nickname and submits a change request back to the server, the most recently rejected change won’t mistakenly pick up penpal recommendation. Because the myId property is declared as a constant, it can’t change locally. As a result, requests to the database won’t accidentally change the wrong record.
-
struct PenPalRecord {
let myID: Int
var myNickname: String
var recommendedPenPalID: Int
}
var myRecord = try JSONDecoder().decode(PenPalRecord.self, from: jsonResponse)
-
Use structures and protocols to model inheritance and share behavior.
-
Structure can’t inherit from classes. However, the kinds of inheritance hierarchies you can build with class inheritance can also be modeled using protocol inheritance and structures.
-
Protocols permit classes, structures, and enumerations to participate in inheritance, while class inheritance is only compatible with other classes. When you are choosing how to model your data, try building the hierarchy of data types using protocol inheritance first, then adopt those protocols in your structures.
-
Choose Classes
-
when you need to control identity (===)
-
Common use cases are file handles, network connections, and shared hardware intermediaries like CBCentralManager.
-
If you share a class instance across your app, changes you make to that instance are visible to every part of your code that holds a reference to that instance.
-
local database connection.
-
-
