Structs in Swift
Structs are value types; their values are copied and each variable keeps its own set of values. When we set out to name "Pravesh", the "Ayush" struct in aStudentStruct does not get changed.
- struct Student {
- var name: String
- init(name: String) {
- self.name = name
- }
- }
- var aStudentStruct = Student(name:"Ayush")
- var bStudentStruct = aStudentStruct
- bStudentStruct.name = "Pravesh"
- println(aStudentStruct.name)
- println(bStudentStruct.name)
Class in Swift
A class is a reference type and passed by reference. Also, classes have Inheritance which allows one class to inherit the characteristics of another.
Here's an example of a Swift class. When the name is changing, the instance referenced by both variables is updated. "Ayush" is now "Pravesh" everywhere the "Ayush" name was ever referenced.
- class StudentClass {
- var name: String
- init(name: String) {
- self.name = name
- }
- }
- var aStudentClass = StudentClass(name:"Ayush")
- var bStudentClass = aStudentClass
- bStudentClass.name = "Pravesh"
- println(aStudentClass.name)
- println(bStudentStruct.name)
Structs and classes in Swift have many things in common. 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.
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 the class to free up any resources it has assigned.
- Reference counting allows more than one reference to a class
Enum in Swift
An enumeration defines a common type for a group of related values and enables you to work with those values in a type-safe way within your code, the enumeration in Swift is first-class types in their own right.
Enum is considered as a structured data type that can be modified without needing to change, say, a String or Int multiple times within yours.
- let myString = "Pravesh"
- if myString == "Pravesh Dubey" {
-
- }
With an enum, we can avoid this and never worry about changing the same thing more than once.
- enum MyEnum: String {
- case Test = "Pravesh"
- }
- let enumValue = MyEnum.Test
-
- if enumValue == MyEnum.Test {
-
- }
Enums are initialized by one of a finite number of cases, are completely defined by their case, and should always show the valid instance of that case when instantiated.