[go: up one dir, main page]

0% found this document useful (0 votes)
30 views1 page

Struct Vs Class

Uploaded by

Amazing Deals
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views1 page

Struct Vs Class

Uploaded by

Amazing Deals
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

```

Closures in Swift provide a concise and expressive way to write functions or blocks of code. They
are particularly powerful when used in conjunction with higher-order functions or as completion
handlers for asynchronous operations.

Q: What is the difference between a struct and a class in Swift? When would you
use one over the other?
In Swift, both structs and classes are used to define custom data types and structures. While they
share some similarities, there are key differences between them. Understanding these differences is
crucial for choosing the appropriate type for a given scenario. Here are the main distinctions
between structs and classes:

1. Value vs. Reference Types:


- Structs:
- Value types. When a struct is assigned to a new variable or passed as a function argument, a
copy of the entire value is made.
- Each instance is independent, and modifications to one instance do not affect others.

- Classes:
- Reference types. When a class instance is assigned to a new variable or passed as a function
argument, both variables reference the same instance in memory.
- Modifications to one instance are visible to all references pointing to that instance.

2. Identity and Equality:


- Structs:
- Compared based on their values. Two instances are considered equal if all their properties are
equal.
- Each instance has its own unique identity.

- Classes:
- Compared based on reference identity. Two references are equal only if they point to the same
instance in memory.
- Instances can share the same identity.

3. Mutability:
- Structs:
- By default, instances are immutable. If you want to modify the properties of a struct, you need
to use the `mutating` keyword on the methods that modify the instance.

- Classes:
- Instances are mutable by default. You can modify properties and call methods without the
need for the `mutating` keyword.

4. Inheritance:
- Structs:
- Cannot inherit from other types. They do not support inheritance.

- Classes:
- Support class inheritance. A class can inherit properties and behaviors from another class.

You might also like