Updated 31 August 2020
Class And Structure in swift are good choices for storing data and modeling behavior in your apps, but their similarities can make it difficult to choose one over the other.
Consider the following recommendations to help choose which option makes sense when adding a new data type to your app.
Class And Structure in swift are general-purpose, flexible constructs that become the building blocks of your program’s code. You define properties and methods to add functionality to your structures and classes using the same syntax you use to define constants, variables, and functions.
Structures and classes in Swift have many things in common. Both can:
Classes have additional capabilities that structures don’t have:
Since a class is a reference type and it supports inheritance, the complexity increases. In most cases, a struct should be enough to meet your needs. Use a class when they’re appropriate or necessary
To demonstrate the difference between classes
and structs
, first design a class, HumanClass
that has a name
property.
1 2 3 4 5 |
class TestClass { name: String init(name: String) { self.name = name } } |
1 2 |
var ClassObject = TestClass(name: "Bob") ClassObject.name // "Bob" |
Create another instance that “copies” humanClassObject
1 |
let newClassObject = ClassObject |
Change the name
property of newHumanClassObject
to “Bobby”.
1 2 |
ClassObject.name = "Bobby" newClassObject.name // "Bobby" |
The name
property of newHumanClassObject
has been changed to “Bobby” as well.
Thanks for reading this blog, this will help you to add the class or structure in your project and You can know more from here.
So pls follow the above step and And if you have any issue or suggestion you can leave your message in the comment section I will try to solve this.
Be the first to comment.
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Struct Design
Let us find out if the same behavior occurs with an object created with
structs
Create Instance
Create another instance that “copies”
structObject
Change the
name
property ofstructObject
to “Bobby”.On the contrary, the change in the
name
property ofstructObject
has no effect onnewStructObject.name
.The graph below shows the fundamental difference between
value types
vsreference types
.