
Domains
Agile Management
Master Agile methodologies for efficient and timely project delivery.
View All Agile Management Coursesicon-refresh-cwCertifications
Scrum Alliance
16 Hours
Best Seller
Certified ScrumMaster (CSM) CertificationScrum Alliance
16 Hours
Best Seller
Certified Scrum Product Owner (CSPO) CertificationScaled Agile
16 Hours
Trending
Leading SAFe 6.0 CertificationScrum.org
16 Hours
Professional Scrum Master (PSM) CertificationScaled Agile
16 Hours
SAFe 6.0 Scrum Master (SSM) CertificationAdvanced Certifications
Scaled Agile, Inc.
32 Hours
Recommended
Implementing SAFe 6.0 (SPC) CertificationScaled Agile, Inc.
24 Hours
SAFe 6.0 Release Train Engineer (RTE) CertificationScaled Agile, Inc.
16 Hours
Trending
SAFe® 6.0 Product Owner/Product Manager (POPM)IC Agile
24 Hours
ICP Agile Certified Coaching (ICP-ACC)Scrum.org
16 Hours
Professional Scrum Product Owner I (PSPO I) TrainingMasters
32 Hours
Trending
Agile Management Master's Program32 Hours
Agile Excellence Master's ProgramOn-Demand Courses
Agile and ScrumRoles
Scrum MasterTech Courses and Bootcamps
Full Stack Developer BootcampAccreditation Bodies
Scrum AllianceTop Resources
Scrum TutorialProject Management
Gain expert skills to lead projects to success and timely completion.
View All Project Management Coursesicon-standCertifications
PMI
36 Hours
Best Seller
Project Management Professional (PMP) CertificationAxelos
32 Hours
PRINCE2 Foundation & Practitioner CertificationAxelos
16 Hours
PRINCE2 Foundation CertificationAxelos
16 Hours
PRINCE2 Practitioner CertificationSkills
Change ManagementMasters
Job Oriented
45 Hours
Trending
Project Management Master's ProgramUniversity Programs
45 Hours
Trending
Project Management Master's ProgramOn-Demand Courses
PRINCE2 Practitioner CourseRoles
Project ManagerAccreditation Bodies
PMITop Resources
Theories of MotivationCloud Computing
Learn to harness the cloud to deliver computing resources efficiently.
View All Cloud Computing Coursesicon-cloud-snowingCertifications
AWS
32 Hours
Best Seller
AWS Certified Solutions Architect - AssociateAWS
32 Hours
AWS Cloud Practitioner CertificationAWS
24 Hours
AWS DevOps CertificationMicrosoft
16 Hours
Azure Fundamentals CertificationMicrosoft
24 Hours
Best Seller
Azure Administrator CertificationMicrosoft
45 Hours
Recommended
Azure Data Engineer CertificationMicrosoft
32 Hours
Azure Solution Architect CertificationMicrosoft
40 Hours
Azure DevOps CertificationAWS
24 Hours
Systems Operations on AWS Certification TrainingAWS
24 Hours
Developing on AWSMasters
Job Oriented
48 Hours
New
AWS Cloud Architect Masters ProgramBootcamps
Career Kickstarter
100 Hours
Trending
Cloud Engineer BootcampRoles
Cloud EngineerOn-Demand Courses
AWS Certified Developer Associate - Complete GuideAuthorized Partners of
AWSTop Resources
Scrum TutorialIT Service Management
Understand how to plan, design, and optimize IT services efficiently.
View All DevOps Coursesicon-git-commitCertifications
Axelos
16 Hours
Best Seller
ITIL 4 Foundation CertificationAxelos
16 Hours
ITIL Practitioner CertificationPeopleCert
16 Hours
ISO 14001 Foundation CertificationPeopleCert
16 Hours
ISO 20000 CertificationPeopleCert
24 Hours
ISO 27000 Foundation CertificationAxelos
24 Hours
ITIL 4 Specialist: Create, Deliver and Support TrainingAxelos
24 Hours
ITIL 4 Specialist: Drive Stakeholder Value TrainingAxelos
16 Hours
ITIL 4 Strategist Direct, Plan and Improve TrainingOn-Demand Courses
ITIL 4 Specialist: Create, Deliver and Support ExamTop Resources
ITIL Practice TestData Science
Unlock valuable insights from data with advanced analytics.
View All Data Science Coursesicon-dataBootcamps
Job Oriented
6 Months
Trending
Data Science BootcampJob Oriented
289 Hours
Data Engineer BootcampJob Oriented
6 Months
Data Analyst BootcampJob Oriented
288 Hours
New
AI Engineer BootcampSkills
Data Science with PythonRoles
Data ScientistOn-Demand Courses
Data Analysis Using ExcelTop Resources
Machine Learning TutorialDevOps
Automate and streamline the delivery of products and services.
View All DevOps Coursesicon-terminal-squareCertifications
DevOps Institute
16 Hours
Best Seller
DevOps Foundation CertificationCNCF
32 Hours
New
Certified Kubernetes AdministratorDevops Institute
16 Hours
Devops LeaderSkills
KubernetesRoles
DevOps EngineerOn-Demand Courses
CI/CD with Jenkins XGlobal Accreditations
DevOps InstituteTop Resources
Top DevOps ProjectsBI And Visualization
Understand how to transform data into actionable, measurable insights.
View All BI And Visualization Coursesicon-microscopeBI and Visualization Tools
Certification
24 Hours
Recommended
Tableau CertificationCertification
24 Hours
Data Visualization with Tableau CertificationMicrosoft
24 Hours
Best Seller
Microsoft Power BI CertificationTIBCO
36 Hours
TIBCO Spotfire TrainingCertification
30 Hours
Data Visualization with QlikView CertificationCertification
16 Hours
Sisense BI CertificationOn-Demand Courses
Data Visualization Using Tableau TrainingTop Resources
Python Data Viz LibsCyber Security
Understand how to protect data and systems from threats or disasters.
View All Cyber Security Coursesicon-refresh-cwCertifications
CompTIA
40 Hours
Best Seller
CompTIA Security+EC-Council
40 Hours
Certified Ethical Hacker (CEH v12) CertificationISACA
22 Hours
Certified Information Systems Auditor (CISA) CertificationISACA
40 Hours
Certified Information Security Manager (CISM) Certification(ISC)²
40 Hours
Certified Information Systems Security Professional (CISSP)(ISC)²
40 Hours
Certified Cloud Security Professional (CCSP) Certification16 Hours
Certified Information Privacy Professional - Europe (CIPP-E) CertificationISACA
16 Hours
COBIT5 Foundation16 Hours
Payment Card Industry Security Standards (PCI-DSS) CertificationOn-Demand Courses
CISSPTop Resources
Laptops for IT SecurityWeb Development
Learn to create user-friendly, fast, and dynamic web applications.
View All Web Development Coursesicon-codeBootcamps
Career Kickstarter
6 Months
Best Seller
Full-Stack Developer BootcampJob Oriented
3 Months
Best Seller
UI/UX Design BootcampEnterprise Recommended
6 Months
Java Full Stack Developer BootcampCareer Kickstarter
490+ Hours
Front-End Development BootcampCareer Accelerator
4 Months
Backend Development Bootcamp (Node JS)Skills
ReactOn-Demand Courses
Angular TrainingTop Resources
Top HTML ProjectsBlockchain
Understand how transactions and databases work in blockchain technology.
View All Blockchain Coursesicon-stop-squareBlockchain Certifications
40 Hours
Blockchain Professional Certification32 Hours
Blockchain Solutions Architect Certification32 Hours
Blockchain Security Engineer Certification24 Hours
Blockchain Quality Engineer Certification5+ Hours
Blockchain 101 CertificationOn-Demand Courses
NFT Essentials 101: A Beginner's GuideTop Resources
Blockchain Interview QsProgramming
Learn to code efficiently and design software that solves problems.
View All Programming Coursesicon-codeSkills
Python CertificationInterview Prep
Career Accelerator
3 Months
Software Engineer Interview PrepOn-Demand Courses
Data Structures and Algorithms with JavaScriptTop Resources
Python TutorialIn this lesson, we will learn about the different data types in Swift:
Any programming language's data type consists of a set of information with set meanings and distinctive variables. You must use different types of variables to store information while programming in any programming language. Variables are nothing more than reserved storage locations. This means that you reserve some space in the memory when creating a variable.
You can save information on different types of data like strings, characters, widespread characters, integer, boolean, etc. The operating system allocates memory on the basis of a variable data type and decides what is stored within the storage space.The Swift language provides different kinds of data types. The following are some of them:
This is an ordered character set. "Hi, World!" for instance.You can create a String either by using a string literal or creating an instance of a String class as follows −
// Example String literal
var stringX ="Hello, World 1!"
print( stringX )
// Example String instance
var stringY =String("Hello, World 2!")
print( stringY )
//Example Multiple line string
let stringZ ="""
Hey this is a
example of multiple Line
string
"""
print(stringZ)
The output for the above programme would be as follows:
Hello, World 1!
Hello, World 2!
Hey this is a
example of multiple Line
string
Now we will discuss some scenarios where the string data type is used.
You can create an empty string either through a literal empty string or by creating a string class instance as shown below. The boolean property isEmpty can also be used to check whether the string is empty.
// Example String literal
var stringX = ""
if stringX.isEmpty {
print( "stringX is empty")
} else {
print( "stringX is not empty")
}
// Example String instance
let stringY = String()
if stringY.isEmpty {
print( "stringY is empty")
} else {
print( "stringY is not empty")
}
You can indicate whether your string can be changed by assigning it to a variable or whether it is constant by assigning it to a constant by the keyword let as shown below.
// stringX can be modified
var stringX = "Hello, World!"
stringX + = "--Example--"
print( stringX )
// stringY can not be modified
let stringY = String("Hello, World!")
stringY + = "--Example--"
print( stringY )
The above program will give compilation error as we are trying to modify the second string which has been declared as constant.
Playground execution failed: error: <EXPR>:10:1: error: 'String' is not
convertible to '@lvalue UInt8'
stringY + = "--Example--"
String interpolation is a way to construct a new string value by including the value within a literal string from a mix of constants, variables, literals and expressions.
var varX = 30
let constX = 20
var varY:Float = 20.0
var stringX = "\(varX) times \(constX) is equal to \(varX * 20)"
print( stringX )
The output would be:
30 times 20 is equal to 600.0
You can configure two strings or strings and a character or two characters with + operator. An easy example is here −
let constX = "Hello,"
let constY = "World!"
var stringX = constX + constY
print( stringX)
Swift strings have no length property, but you can count the number of characters in a string using the global count () function.
var varX = "Hello, World 4!"
print( "\(varA), length is \((varA.count))")
The== operator can be used to compare two string variables or constants strings. This is a straightforward instance −
var varA = "Hello, World!"
var varB = "Hello, World!"
if varA == varB {
print( "\(varA) and \(varB) are equal")
} else {
print( "\(varA) and \(varB) are not equal")
}
Swift promotes a broad variety of string-related methods and operators.
Functions/Operators | Purpose |
|---|---|
| A Boolean value which tells whether or not a string is empty. |
| Function to verify if a specified string is available as a string prefix or not. |
| The function of checking if a particular string parameter exists as a string suffix or not. |
| Function to convert numeric String value into Integer. |
| Global character counting function in a string. |
| Returning property of a string UTF-8 representation. |
| Returning property of a string UTF16 representation. |
| Property to return a string representation of Unicode Scalar. |
| Two strings or one string and one character or two characters are connected by an operator. |
| Operator for a current string to attach a string or character. |
| Two-string equality determination operator. |
| Operator to conduct a lexicographical comparison to determine if one string is less than another. |
| To get the value at starting index of string. |
| To get the value at ending index of string. |
| To access the indices one by one. i.e all the characters of string one by one. |
| ("Value", at: position)To insert a value at a position. |
| to remove a value at a position. |
| to remove a range of values from string. |
reversed() | returns the reverse of a string |
This is a literal string of one character. "F" for instance.
let char1:Character="X"
let char2:Character="Y"
print("Value of char1 \(char1)")
print("Value of char2 \(char2)")
If you attempt to store multiple characters in a Character type variable or constant, Swift will not allow that. In Swift you will try to write the instance below, and even before compilation you will get an error.
// Trying to store multiple characters
letchar: Character = "AB"
print("Value of char \(char)")
Also It is not possible to create an empty Character variable or constant which will have an empty value.
// Following is wrong in Swift
let char1: Character = ""
var char2: Character = ""
As described, string reflects a collection in a defined order of character values. Thus we can use a for-in-loop iteration to access individual characters on the specified string.
for ch in"Hello World" {
print(ch)
}
The following instance shows how a string can be combined with a character.
var varX:String = "Hello "
let varY:Character = "W"
varX.append( varY)
print("Value of varZ = \(varX)")
Swift arrays are used in ordered lists of any particular sort to store various values. Swift establishes strict control mechanisms that enable programmers not to enter or insert any false types into an array even by mistake, i.e., arrays in swift programming are specific about the kinds of values they can store. In a swift array at distinct locations, the same value may occur. The swift arrays vary from the NSArray and NSMutableArray classes of Objective-C which can store any item and provide no information on the nature of the objects it returns. In Swift it is always evident what sort of values a specific array can store, either via an explicit type annotation or a type inference, without having to be a class form. Swift arrays are secure, and what they may contain is always evident.
The swift array can be represented in the format as the array < SomeType > in which the array will be stored as' SomeType.' Programmers can also write an array type as SomeType[] shorthand. While the two forms mentioned are functionally the same, the shorter form is preferred rather than the other. If programmers assign a variable to an already current array, it is always changeable. This implies that the programmer has the option to alter it, add, delete or alter its elements. But when a constant is assigned to the arrays, the array is immutable and cannot change its size and content.
The following initializer syntax allows you to generate an empty array of a certain type. −
var someArray = [SomeType]()
This is the syntax for the creation, initialisation and value of an array of a given size a* −
var someArray = [SomeType](count: NumberOfElements, repeatedValue:InitialValue)
You can create an empty Int-type array with three elements and the initial value as zero with the following statement. −
var someInts = [Int](count: 3, repeatedValue:0)
Following is one more example to create an array of three elements and assign three values to that array −
var someInts:[Int] = [10, 20, 30]
By using a subscription syntax, you can get a value from an array and instantly after you get an index of the value that you want to recover from the array.
var someInts =[Int](count:3, repeatedValue:10)
var someVar = someInts[0]
print("Value of first element is \(someVar)")
print("Value of second element is \(someInts[1])")
print("Value of third element is \(someInts[2])")
You can add a fresh object on the end of an array using the append or the addition of an assignment operator (+ =). Check out the example below. We generate an empty array here at first, and then add fresh components to the same array.
var someInts = [Int]()
someInts.append(20)
someInts.append(30)
someInts += [40]
var someVar = someInts[0]
print( "Value of first element is \(someVar)")
print( "Value of second element is \(someInts[1])")
print( "Value of third element is \(someInts[2])")
To find out whether or not an array is emptied, you may use the read only empty property of an array.
var intsA = [Int](count:2, repeatedValue: 2)
var intsB = [Int](count:3, repeatedValue: 1)
var intsC = [Int]()
print("intsA.isEmpty = \(intsA.isEmpty)")
print("intsB.isEmpty = \(intsB.isEmpty)")
print("intsC.isEmpty = \(intsC.isEmpty)")
To find out the following numbers of items in an array, you can use the read-only count property of an array.
var intsA = [Int](count:2, repeatedValue: 2)
var intsB = [Int](count:3, repeatedValue: 1)
var intsC = intsA + intsB
print("Total items in intsA = \(intsA.count)")
print("Total items in intsB = \(intsB.count)")
print("Total items in intsC = \(intsC.count)")
You can combine two arrays with the same type using the addition operator (+) to create a fresh array with a mix of values from both arrays as follows.
var intsA = [Int](count:2, repeatedValue: 2)
var intsB = [Int](count:3, repeatedValue: 1)
var intsC = intsA + intsB
for item in intsC {
print(item)
}
You can use enumerate() to return the index and value of an item, as shown in the following example.
var Strs = [String]()
Strs.append("India")
Strs.append("Srilanka")
Strs += ["Pakistan"]
for (index, item) in Strs.enumerated() {
print("Value at index = \(index) is \(item)")
}
The output of the above program would be as follows:
Value at index = 0 is India
Value at index = 1 is Srilanka
Value at index = 2 is Pakistan
Specific values of the same type are stored in Swift sets, but they don't have definite arrays as ordered.
You can use sets rather than arrays when there is no problem with ordering components or if you want to make sure no duplicate values are present. A type must be hashable to save in a set. (Sets only enable distinct values). A hash value is an Int value that is equal for equal objects. For Example When x= y, then x.hashvalue== y.hashvalue .
All the fundamental Swift values can be used as set values and are by default hashable.
Use the following initializer syntax to produce an empty set of a certain type.
var someSet = Set<Character>() //Character can be replaced by data type of Set.
Use its methods and properties to access or change a set.
someSet.count // prints the number of elements
someSet.insert("c") // adds the element to Set.
someSet.isEmpty // returns true or false depending on the set Elements.
someSet.remove("c") // removes an element , removeAll() can be used to remove all element
someSet.contains("c") // to check if set contains this value.
for items in someSet {
print(someSet)
}
//Swift sets are not in an ordered way, to iterate over a set in an ordered way use
for items in someSet.sorted() {
print(someSet)
}
Some operations on Sets
let evens: Set = [10,12,14,16,18]
let odds: Set = [5,7,9,11,13]
let primes = [2,3,5,7]
odds.union(evens).sorted()
// [5,7,9,10,11,12,13,14,16,18]
odds.intersection(evens).sorted()
//[]
odds.subtracting(primes).sorted()
//[9, 11, 13]
The unordered list of values of the same sort is type stored in dictionaries. Swift makes stringent controls that do not allow you to erroneously enter a false type into a dictionary.
Swift dictionaries use a unique identifier called a key, which can then be referenced and viewed by the same key. Unlike array items, array items have no order in a dictionary. When you have to look for values on the basis of your identifiers, you can use a dictionary.
An integer or a string may be a dictionary key, but it should be unique within a dictionary.
If a generated dictionary is assigned to a variable, it is always mutable that allows you to alter it by adding, removing or modifying its objects. But if you give a dictionary a constant, it is immutable and cannot change its size and content.
var someDict = [KeyType: ValueType]()
Example
Empty Dictionary
var someDict = [Int: String]()
Dictionary with set of values
var someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]
A below example displays how we can use array to declare Dictionary(key-value) pair.
var cities = [“Patna”,”Chennai”,”Kolkata”,”Bangalore”]
var Distance = [3000,2500, 620,700]
let cityDistanceDict = Dictionary(uniqueKeysWithValues: zip(cities, Distance))
The above program will create a dictionary with cities as key and distance as value.
We can run below program for filtering cities having distance less than 1000.
var closeCities = cityDistanceDict.filter { $0.value < 1000}
The output would be
["Kolkata" : 620, "Banglore" : 700]
We can also apply grouping in dictionary with below syntax. If we would like to group cities based on first alphabet.
var cities = ["Delhi","Bangalore","Hyderabad","Dehradun","Bihar"]
var GroupedCities = Dictionary(grouping: cities ) { $0.first! }
Then output would be
["D" :["Delhi","Dehradun"], "B" : ["Bengaluru","Bihar"], "H" : ["Hyderabad"]]
By using a subscription syntax, you can recover a value from a dictionary by passing the value key you want to collect from the dictionary right after the dictionary name.
var someVar = someDict[key]
To add current value to a specified dictionary key, you can use updateValue(forKey:) technique. This technique returns an optional value of the type of value of the dictionary.
var someDict:[Int:String] = [1:"hello", 2:"World", 3:"Example"]
var oldVal = someDict.updateValue("New value of one-hello", forKey:1)
var someVar = someDict[1]
print( "Old value of key = 1 is \(oldVal)")
print( "new Value of key = 1 is \(someVar)")
The output would be
Old value of key = 1 is Optional("hello")
Value of key = 1 is Optional("New value of one-hello")
To remove a key value pair from a dictionary, you can use the removeValueForKey() method. This technique removes the key value pair, if it exists, and returns the deleted value.
var someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]
var removedValue = someDict.removeValue(forKey: 2)
//There is an alternative way as well someDict[2] = nil
print( "Value of key = 2 is \(someDict[2])")
The output would be
Value of key = 2 is nil
The whole series of key value pairs of a dictionary can be iterated using a for-in loop, as shown in this example.
var someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]
for (index, keyValue) in someDict.enumerated() {
print("Dictionary key \(index) - Dictionary value \(keyValue)")
}
The enumerate() method can be used to return the index of the item along with its (key, value).
var someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]
for (key, value) in someDict.enumerated() {
print("Dictionary key \(key) - Dictionary value \(value)")
}
This module gave us fair idea of inbuilt data types being used in swift. We have found similarities in swift data types with other programming language data types. Swift has also similar data types for strings, characters, array, sets, and dictionaries.