top

Search

Swift Tutorial

An enumeration describes a common type for an associated value group and allows you to work with those values within your code in a type-safe manner. If you're acquainted with C, you'll understand that a set of integer values are assigned by C enumerations. Swift enumerations are much more flexible and do not have to provide a value for each enumeration case. If a value (known as a raw value) is provided for each enumeration case, the value may be a string, a character, or any kind of integer or floating point value. Alternatively, enumeration instances may indicate related values of any type to be stored together with each individual case value, just as unions or variations do in other languages. As part of a single enumeration, you can identify a common set of related instances, each of which has a distinct set of values connected with suitable kinds. Swift enumerations  are top notch class types. They embrace numerous highlights generally bolstered distinctly by classes, for example, we get some more information on enumeration’s current value , and methods to manipulate values represented by enumerations. The initializers can be also defined in enumerations to initialize enumeration case values. Enumerations functionality  can be expanded beyond their initial execution; and can adhere to protocols to provide normal functionality. The enum keyword introduces enumerations and places their entire definition in a couple of braces. Syntaxenum enumname {     // enumeration values are described here  } For example, for direction  you can define an enumeration as follows. enumCompassPoint { casenorth casesouth caseeast casewest }The values defined in an enumeration (such as north, south, east, and west) are its enumeration cases. You use the case keyword to introduce new enumeration cases. Consider below example for more clarity. enum names { case Hello case World } var lang = names.World lang =.World switch lang { case.Hello: print("Welcome to Hello") case.World: print("Welcome to World") default: print("Introduction") }The output for the above program would beWelcome to WorldSwift enumeration does not assign the default value of its members such as C and Objective C. Instead, its enumeration names explicitly define the members. The name of the enumeration should begin with a capital letter (e.g., enum DaysofaWeek).var weekDay = DaysofaWeek.MondayHere a variable weekday, Monday is given the name of the enumeration' DaysofaWeek.' It tells the compiler that the datatype belonging to that specific class will be allocated to subsequent enum members. Members can be obtained through passing values and additional calculations once the datatype of the enum member is defined.Enumeration can be further classified into associated values and raw values.Difference between Associated Values and Raw ValuesAssociated ValuesRaw ValuesData Types  are different Ex: enum {15,1.8,"World"}Datatypes same Ex: enum {Jan,Feb,Mar}The constant or variable decides value .It has always prepopulated valuesEach time it is stated, it varies.Member value is identicalAssociated values Enumenum Planet {     case mercury, venus, earth, mars, jupiter, saturn, uranus, neptune }The examples in the past sections demonstrate how the enumeration instances are in their own right a specified (and typed) value. You can put Planet.earth to a constant or variable, and later verify this value. However, in addition to these case values, it is sometimes helpful to be able to store values of other kinds. This additional data is referred to as an associated value, and it differs as a value in your software every moment you use it.To store associated values of any given type, you can define Swift enumerations, and if necessary, the value types may differ for each enumeration case. Similar enumerations are known in other programming languages as discriminated unions, tagged unions, or variations.For instance, assume an inventory monitoring scheme requires two distinct kinds of barcode to track products. Some products are marked in UPC format with 1D barcodes, using digits 0 to 9. Each barcode has a digit amount, followed by five digits of the manufacturer's code and five digits of the product code. A check digit follows these to confirm that the code has been properly scanned.Other products are marked in QR code format with 2D barcodes that can use any ISO 8859-1 character and encode up to 2,953 characters in a string.Storing UPC barcodes as a tuple of four integers and QR code barcodes as a string of any duration is useful for an inventory monitoring scheme. enum Barcode {     case upc(Int, Int, Int, Int)     case qrCode(String) }This can be read as: "Defines an enumeration form called Barcode, which can either take a upc value with a type related value (Int, Int, Int, Int) or a qrCode value with a type String related value." It simply describes the type of values that barcode constants or variables can store when they are equal to the Barcode.upc or Barcode. QrCode values, but this definition does not provide Int or String values. This instance generates a fresh productBarcode variable and assigns a Barcode.upc value with a related tuple value of (8, 85909, 51226, 3). var productBarcode = Barcode.upc(8, 85909, 51226, 3)You can give another type of barcode to the same item: productBarcode = .qrCode("ABCDEFGHIJKLMNOP")Enum with Raw ValuesRaw values can be strings, characters, or any of the types of integer numbers or floating-points. Each raw value must be distinctive in its statement of enumeration. When using integers for raw values, they will auto-increase if no value is specified for some members of the enumeration. enum Planet: Int {        case mercury = 1, venus, earth, mars, jupiter, saturn, uranus,neptune} let planetUniverse= Planet.mars.rawValue  print("Value of the planet is: \(planetUniverse).") The output would be as follows: 4StructuresSwift offers a flexible construction block to use buildings as structures. By using these structures , methods and properties can be defined once. No execution files and interface are required for the structure. In the Structure, variable values will be copied and transferred to subsequent codes by returning a copy of old values so that values will not be changed. Structure will allow us to generate a single file and expand its interface to other blocks automatically. Syntax Structures are defined with a 'Struct' Keyword. struct nameStruct {    Definition 1    Definition 2    ---    Definition N }Consider, for instance, if we have to access student records containing marks of three topics and find out the total of three topics. MarkStruct is used here to initialize a structure  with three marks as the' Int' data type. struct MarkStruct {    var mark1: Int    var mark2: Int    var mark3: Int }Accessing properties of structure struct topicMarks {    var markTopic1 = 100    var markTopic2 = 200    var markTopic3 = 300 } let marks = topicMarks () print("Mark1 is \(marks.markTopic1)") print("Mark2 is \(marks.markTopic2)") print("Mark3 is \(marks.markTopic3)")Using playground, we get the following outcome when we run the above program. Mark1 is 100Mark2 is 200Mark3 is 300 The structure name ' studentMarks' accesses the student marks. The members of the structure are initialized with integer-type values as mark1, mark2, mark3. Then the studentMarks() structure is carried with the keyword' let' to the' marks.' The structure member values will be contained in' marks' below. By accessing the structure member values by'.' with their initialized names, the values are now printed. Example struct MarksStruct{ var mark:Int init(mark:Int){   self.mark = mark  } } var aStruct = MarksStruct(mark:98) var bStruct = aStruct     // aStruct and bStruct are two structs with the same value! bStruct.mark = 97 print(aStruct.mark) // 98 print(bStruct.mark) // 97Swift language offers the features for defining structures to generate function blocks as custom data types. The instances of structures are passed by its value for doing any further manipulations to defined blocks. Memberwise Initializers for Structure Types All structures have a memberwise initializerautomatically generated, to initialize the member characteristics of new structure instances. Initial values for the new structure characteristics can be passed by name to the member initializer. let vga = Resolution(width: 640, height: 480)Why do programmers need structures For simple data values to encapsulate.For copying encapsulated data  and related properties by 'values' instead ofreferences.Copy and Reference Structure.Summary:We covered concept of enumeration and structures in this module. We have got fair idea of when to use enumeration and when to use structures in swift. Also we found striking similarities in other programming languages concept of enumeration and structures.
logo

Swift Tutorial

Enumerations & Structures

An enumeration describes a common type for an associated value group and allows you to work with those values within your code in a type-safe manner. 

If you're acquainted with C, you'll understand that a set of integer values are assigned by C enumerations. Swift enumerations are much more flexible and do not have to provide a value for each enumeration case. If a value (known as a raw value) is provided for each enumeration case, the value may be a string, a character, or any kind of integer or floating point value. 

Alternatively, enumeration instances may indicate related values of any type to be stored together with each individual case value, just as unions or variations do in other languages. As part of a single enumeration, you can identify a common set of related instances, each of which has a distinct set of values connected with suitable kinds. 

Swift enumerations  are top notch class types. They embrace numerous highlights generally bolstered distinctly by classes, for example, we get some more information on enumeration’s current value , and methods to manipulate values represented by enumerations. The initializers can be also defined in enumerations to initialize enumeration case values. Enumerations functionality  can be expanded beyond their initial execution; and can adhere to protocols to provide normal functionality. 

The enum keyword introduces enumerations and places their entire definition in a couple of braces. 

Syntax

enum enumname { 
   // enumeration values are described here 
} 

For example, for direction  you can define an enumeration as follows. 

enumCompassPoint {
casenorth
casesouth
caseeast
casewest
}

The values defined in an enumeration (such as north, south, east, and west) are its enumeration cases. You use the case keyword to introduce new enumeration cases. 

Consider below example for more clarity. 

enum names {
 case Hello
 case World
}

var lang = names.World
lang =.World

switch lang {
 case.Hello:
  print("Welcome to Hello")
case.World:
print("Welcome to World")
default:
print("Introduction")
}

The output for the above program would be

Welcome to World

Swift enumeration does not assign the default value of its members such as C and Objective C. Instead, its enumeration names explicitly define the members. The name of the enumeration should begin with a capital letter (e.g., enum DaysofaWeek).

var weekDay = DaysofaWeek.Monday

Here a variable weekday, Monday is given the name of the enumeration' DaysofaWeek.' It tells the compiler that the datatype belonging to that specific class will be allocated to subsequent enum members. Members can be obtained through passing values and additional calculations once the datatype of the enum member is defined.

Enumeration can be further classified into associated values and raw values.

Difference between Associated Values and Raw Values

Associated ValuesRaw Values
Data Types  are different Ex: enum {15,1.8,"World"}Datatypes same Ex: enum {Jan,Feb,Mar}
The constant or variable decides value .It has always prepopulated values
Each time it is stated, it varies.Member value is identical

Associated values Enum

enum Planet {
    case mercury, venus, earth, mars, jupiter, saturn, uranus, neptune
}

The examples in the past sections demonstrate how the enumeration instances are in their own right a specified (and typed) value. You can put Planet.earth to a constant or variable, and later verify this value. However, in addition to these case values, it is sometimes helpful to be able to store values of other kinds. This additional data is referred to as an associated value, and it differs as a value in your software every moment you use it.

To store associated values of any given type, you can define Swift enumerations, and if necessary, the value types may differ for each enumeration case. Similar enumerations are known in other programming languages as discriminated unions, tagged unions, or variations.For instance, assume an inventory monitoring scheme requires two distinct kinds of barcode to track products. Some products are marked in UPC format with 1D barcodes, using digits 0 to 9. Each barcode has a digit amount, followed by five digits of the manufacturer's code and five digits of the product code. A check digit follows these to confirm that the code has been properly scanned.

Other products are marked in QR code format with 2D barcodes that can use any ISO 8859-1 character and encode up to 2,953 characters in a string.

Storing UPC barcodes as a tuple of four integers and QR code barcodes as a string of any duration is useful for an inventory monitoring scheme. 

enum Barcode {
    case upc(Int, Int, Int, Int)
    case qrCode(String)
}

This can be read as: "Defines an enumeration form called Barcode, which can either take a upc value with a type related value (Int, Int, Int, Int) or a qrCode value with a type String related value." It simply describes the type of values that barcode constants or variables can store when they are equal to the Barcode.upc or Barcode. QrCode values, but this definition does not provide Int or String values. 

This instance generates a fresh productBarcode variable and assigns a Barcode.upc value with a related tuple value of (8, 85909, 51226, 3). 

var productBarcode = Barcode.upc(8, 85909, 51226, 3)

You can give another type of barcode to the same item: 

productBarcode = .qrCode("ABCDEFGHIJKLMNOP")

Enum with Raw Values

Raw values can be strings, characters, or any of the types of integer numbers or floating-points. Each raw value must be distinctive in its statement of enumeration. When using integers for raw values, they will auto-increase if no value is specified for some members of the enumeration. 

enum PlanetInt { 
       case mercury = 1venusearthmarsjupitersaturnuranus,neptune} 
let planetUniverse= Planet.mars.rawValue 
print("Value of the planet is: \(planetUniverse).")

The output would be as follows:
4

Structures

Swift offers a flexible construction block to use buildings as structures. By using these structures , methods and properties can be defined once. No execution files and interface are required for the structure. In the Structure, variable values will be copied and transferred to subsequent codes by returning a copy of old values so that values will not be changed. Structure will allow us to generate a single file and expand its interface to other blocks automatically. 

Syntax 

Structures are defined with a 'Struct' Keyword.
struct nameStruct {
   Definition 1
   Definition 2
   ---
   Definition N
}

Consider, for instance, if we have to access student records containing marks of three topics and find out the total of three topics. MarkStruct is used here to initialize a structure  with three marks as the' Int' data type. 

struct MarkStruct {
   var mark1: Int
   var mark2: Int
   var mark3: Int
}

Accessing properties of structure 

struct topicMarks {
   var markTopic1 = 100
   var markTopic2 = 200
   var markTopic3 = 300
}

let marks = topicMarks ()
print("Mark1 is \(marks.markTopic1)")
print("Mark2 is \(marks.markTopic2)")
print("Mark3 is \(marks.markTopic3)")

Using playground, we get the following outcome when we run the above program. 

Mark1 is 100
Mark2 is 200
Mark3 is 300 

The structure name ' studentMarks' accesses the student marks. The members of the structure are initialized with integer-type values as mark1, mark2, mark3. Then the studentMarks() structure is carried with the keyword' let' to the' marks.' The structure member values will be contained in' marks' below. By accessing the structure member values by'.' with their initialized names, the values are now printed. 

Example 

struct MarksStruct{
 var mark:Int

 init(mark:Int){
  self.mark = mark
 }
}

var aStruct = MarksStruct(mark:98)
var bStruct = aStruct     // aStruct and bStruct are two structs with the same value!
bStruct.mark = 97
print(aStruct.mark) // 98
print(bStruct.mark) // 97

Swift language offers the features for defining structures to generate function blocks as custom data types. The instances of structures are passed by its value for doing any further manipulations to defined blocks. 

Memberwise Initializers for Structure Types 

All structures have a memberwise initializerautomatically generated, to initialize the member characteristics of new structure instances. Initial values for the new structure characteristics can be passed by name to the member initializer. 

let vga = Resolution(width: 640, height: 480)

Why do programmers need structures 

  • For simple data values to encapsulate.
  • For copying encapsulated data  and related properties by 'values' instead ofreferences.
  • Copy and Reference Structure.

Summary:

We covered concept of enumeration and structures in this module. We have got fair idea of when to use enumeration and when to use structures in swift. Also we found striking similarities in other programming languages concept of enumeration and structures.

Leave a Reply

Your email address will not be published. Required fields are marked *

Suggested Tutorials

R Programming Tutorial

R Programming

C# Tutorial

C# is an object-oriented programming developed by Microsoft that uses the .Net Framework. It utilizes the Common Language Interface (CLI) that describes the executable code as well as the runtime environment. C# can be used for various applications such as web applications, distributed applications, database applications, window applications etc.For greater understanding of this tutorial, a basic knowledge of object-oriented languages such as C++, Java etc. would be beneficial.
C# Tutorial

C# is an object-oriented programming developed by Microsoft that uses ...

Read More

Python Tutorial

Python Tutorial