SlideShare une entreprise Scribd logo
1  sur  55
Télécharger pour lire hors ligne
By: Hossam Ghareeb 
hossam.ghareb@gmail.com 
Part 1 
The Complete Guide For 
Programming Language
Contents. 
● About Swift 
● Hello World! with playground 
● Variables & Constants 
● Printing Output 
● Type Conversion 
● If 
● If with optionals 
● Switch 
● Switch With Ranges. 
● Switch With Tuples. 
● Switch With Value Binding 
● Switch With "Where" 
● Loops 
● Functions 
● Passing & Returning Functions 
● Closures (Blocks) 
● Arrays 
● Dictionaries 
● Enum
About Swift 
● Swift is a new scripting programming language for iOS and OS X 
apps. 
● Swift is easy, flexible and funny. 
● Unlike Objective-C, Swift is not C Compatible. Objective-C is a 
superset of C but Swift is not. 
● Swift is readable like Objective-C and designed to be familiar to 
Objective-C developers. 
● You don't have to write semicolons, but you must write it if you 
want to write multiple statements in single line. 
● You can start writing apps with Swift language starting from 
Xcode 6. 
● Swift doesn't require main function to start with.
Hello World! 
As usual we will start with printing "Hello World" message. We will 
use something called playground to explore Swift language. It's an 
amazing tool to write and debug code without compile or run. 
Create or open an Xcode project 
and create new playground:
Hello World! 
Use "NSLog" or "println" to print message to console. As you see in 
the right side you can see in real time the values of variables or 
console message.
Variables & Constants. 
In Swift, use 'let' for constans and 'var' for variables. In constants you 
can't change the value of a constant after being initialized and you 
must set a value to it. 
Although you use 'var' or 'let' for variables, Swift is typed language. 
The type is written after ':' . You don't have to write the type of 
variable or constant because the compiler will infer it using its initial 
value. 
BUT if you didn't set an initial value or the initial value that you 
provided is not enough to determine the type, you have to explicitly 
type the variable or constants. 
Check examples:
Variables & Constants.
Variables & Constants. 
In Objective-C we used to use mutability, for example: 
NSArray and NSMutableArray or NSString and NSMutableString 
In Swift, when you use var, all objects will be mutable BUT when you 
use let, all objects will be immutable:
Printing Output 
● We introduced the new way to print output using println(). Its 
very similar to NSLog() but NSLog is slower, adds timestamp to 
output message and appear in device log. Println() appear in 
debugger log only. 
● In Swift you can insert values of variables inside String using "()" a 
backslash with parentheses, check example:
Type Conversion 
Swift is unlike other languages, it will not implicitly convert types of 
result of statements. Lets check example in Obj-C : 
In Swift you can't do this. You have to decide the type of result by 
explicitly converting it to Double or Integer. Check next example:
Type Conversion 
Here we should convert any one of them so the two variables be in same 
type. 
Swift guarantees safety in your code and makes you decide the type of 
your result.
If 
● In Swift, you don't have to add parentheses around the condition. 
But you should use them in complex conditions. 
● Curly braces { } are required around block of code after If or else. 
This also provide safety to your code.
If 
● Conditions must be Boolean, true or false. Thus, the next code 
will not work as it was working in Objective-C : 
As you see in Swift, you cannot check in variable directly like 
Objective-C.
If With Optionals 
● You can set the variable value as Optional to indicate that it may 
contain a value or nil. 
● Write question mark "?" after the type of variable to mark it as 
Optional. 
● Think of it like the "weak" property, it may point to an object or nil 
● Use let with If to check the Optional value. If the optional value is 
nil, the conditional will be false. OtherWise, the it will be true and 
the value will be assigned to the constant of let 
Check example:
If With Optionals
Switch 
Switch works in Swift like many other languages but with some new 
features and small differences: 
● It supports any kind of data, not only Integers. It checks for 
equality. 
● Switch statement must be exhaustive. It means that you have to 
cover (add cases for) all possible values for your variable. If you 
can't provide case statement for each value, add a default 
statement to catch other values. 
● When a case is matched in switch, the program exits from the 
switch case and doesn't continue checking next cases. Thus, you 
don't have to explicitly break out the switch at the end of each 
case. 
Check examples:
Switch
Switch Cont. 
● As we said, there is no fallthrough in switch statements and 
therefore break is not required. So code like this will not work in 
Swift: 
● As you see, each case must contain at least one executable 
statement. 
● Multiple matches for single case can be separated by commas and 
no need for fallthrough cases
Switch Cont.
Switch With Ranges. 
● In Swift you can use the range of values for checking in case 
statements. Ranges are identified with "..." in Swift :
Switch With Tuples. 
Tuples are used to group multiple values in a single compound value. 
Each value can be in any type. Values can be with any number as you 
like: 
You can decompose the values of tuples with many ways as you will 
see in examples. Most of time, tuples are used to return multiple 
values from function. Also can be use to enumerate dictionary 
contents as (key, value). Check examples:
Switch With Tuples. 
● Decomposing: 
● Use underscore "_" to ignore parts:
Switch With Tuples. 
● You can use element index to access tuple values. Also you can 
name the elements and access them by name: 
● With dictionary:
Switch With Tuples. 
Using tuples with functions:
Switch With Tuples. 
Now we will see tuples with switch. We will use it in checking that a 
point is located inside a box in grid. Also we want to check if the point 
located on x-axis or y-axis. Here is the gird:
Switch With Tuples.
Switch With Value Binding 
You can bind the values of variables in switch case statements to 
temporary constants to be used inside the case body:
Switch With "Where" 
"Where" is used with case statement to add additional condition. 
Check these examples:
Switch With "Where" 
Another example in using "Where":
Loops 
● Like other languages, you can use for and for-in loops without 
changes. But in Swift you don't have to write the parentheses. 
● for-in loops can iterate any collection of data. Also It can be used 
with ranges
Functions 
● Functions are created using the keyword 'func'. 
● Parentheses are required for functions that don't take params. 
● In parameters you type the name and type of variable between ':' 
● You can describe or name the local variables of function like 
Objective-C by writing the name before the local variable OR add 
'#' if the local variable is already an appropriate name. Check 
examples:
Functions 
● Using names for local variables
Functions 
● In Swift, params are considered as constants and you can't change 
them. 
● To change local variables, copy the values to other variables OR 
tell Swift that this value is not constant by writing 'var' before the 
name:
Functions 
● To return values, you have to write the type of returned info after 
'()' and "->". Use tuples to return multiple values at once. 
● In Swift, you can use default parameter values. BUT be aware that 
when you wanna use function with default-valued params, you 
must write the name of the argument when you wanna use it. 
Check examples:
Functions 
● Using default parameter value: 
● Functions can take variable number of arguments using '...' :
Passing & Returning Functions 
● In Swift, functions are first class objects. Thus they can be passed 
around 
● Every function has type like this: 
● You can pass a function as parameter or return it as a result. 
Check examples:
Passing & Returning Functions
Closures 
● Closures are very similar to blocks in C and Objective-C. 
● Closures are first class type so it can be nested , returned and 
passed as parameter. (Same as blocks in Objective-C) 
● Functions are special cases of closures. 
● Closures are enclosed in curly braces { } , then write the function 
type (arguments) -> (return type), followed by in keyword that 
separate the closure header from the body.
Closures 
● Example #1, using map with an array. map returns an array with 
result of each item
Closures 
● Example #2 of using closure as completion handler when sending 
api request
Closures 
● Example #3, using the built-in "sorted" function to sort any 
collection based on a closure that will decide the compare result 
of any two items
Arrays 
● Arrays in Swift are typed. You have to choose the type of array, 
array of Integers, array of Strings,....etc. That's different from 
Objective-C where you can create array with items of any type. 
● You can write the type of array between square brackets [ ] OR If 
you initialized it with data, Swift will infer the type of array 
implicitly. 
● Arrays by default are mutable arrays, except if you defined it as 
constant using 'let' it will be immutable. 
● Length of array can be know by .count property, and you can 
check if is it empty or not by .isEmpty property.
Arrays 
● Creating and initializing array is easy. Also you can create array 
with certain size and default value for items: 
● For appending items, use 'append' method or "+=" :
Arrays 
● You can retrieve and update array using subscript syntax. You will 
get runtime error if you tried to access item out of bound.
Arrays 
● You can easily iterate over an array using 'for-in' , 'for' or by 
'enumerate'. 'enumerate' gives you the item and its index during 
enumeration.
Dictionaries 
● Dictionary in Swift is similar to one in Objective-C but like Array, 
Dictionary is strongly typed, all keys must be in same type and all 
values must be in same type. 
● Type of Dictionary is inferred by initial values or you have to write 
the type between square brackets [ KeyType, ValueType] 
● Like Arrays, Dictionaries by default are mutable dictionaries, 
except if you defined it as constant using 'let' it will be immutable. 
● Check examples :)
Dictionaries
Enum 
● Enum is very popular concept if you have specific values of 
something. 
● Enum is created by the keyword 'enum' and listing all possible 
cases after the keyword 'case'
Enum 
● Enum can be used easily in switch case but as we know that switch 
in Swift is exhaustive, you have to list all possible cases.
Enum With Associated Values 
● Enum values can be used with associated values. Lets explain with 
an example. Suppose you describe products in your project, each 
product has a barcode. Barcodes have 2 types (UPC, QRCode) 
● UPC code can be represented by 4 Integers (4,88581,01497,3), 
and QR code can be represented by String ("ABCFFDF")
Enum With Associated Values 
● So we need to represent the barcode with two condition UPC and 
QR , each one has associated values to give full information.
Enum With Raw Values 
● For sure in some cases you need to define some constants in 
enum with their values. For example the power of monster has 
different values based on game level (easy = 50, medium = 60, 
hard = 80, very hard = 120) and these values are constant. So you 
need to make enum for power values and in same time save these 
values. You can create enum with cases values but they must be in 
same type and this type is written after enum name. Also you can 
use .rawValue to get the constant value. 
● You can initialize an enum value using its constant value using this 
format EnumName(rawValue: value). It returns the enum that 
map to the given value. Be careful because the value returned is 
Optional, it may contain an enum or nil, BECAUSE Swift can 
guarantee that the given constant is exist in enum or not.
Enum With Raw Values Example:
Enum With Raw Values Example: 
● Raw values can be Strings, Chars, Integers or floating point 
numbers. In using Integers as a type for raw values, if you set a 
value of any case, others auto_increment if you didn't specify 
values for them.
Thanks 
We have finished Part 1. 
In next parts we will talk about Classes, Structures, OOP and some 
advanced features of Swift. 
If you liked the tutorial, please share and tweet with your friends. 
If you have any comments or questions, don't hesitate to email ME

Contenu connexe

Tendances

Swift Programming Language
Swift Programming LanguageSwift Programming Language
Swift Programming LanguageGiuseppe Arici
 
Swift programming language
Swift programming languageSwift programming language
Swift programming languageNijo Job
 
A swift introduction to Swift
A swift introduction to SwiftA swift introduction to Swift
A swift introduction to SwiftGiordano Scalzo
 
Introduction to Object Oriented Programming
Introduction to Object Oriented ProgrammingIntroduction to Object Oriented Programming
Introduction to Object Oriented ProgrammingMoutaz Haddara
 
Basic iOS Training with SWIFT - Part 1
Basic iOS Training with SWIFT - Part 1Basic iOS Training with SWIFT - Part 1
Basic iOS Training with SWIFT - Part 1Manoj Ellappan
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to javaSaba Ameer
 
Intro to UIKit • Made by Many
Intro to UIKit • Made by ManyIntro to UIKit • Made by Many
Intro to UIKit • Made by Manykenatmxm
 
Introduction to object oriented programming
Introduction to object oriented programmingIntroduction to object oriented programming
Introduction to object oriented programmingAbzetdin Adamov
 
Advance C# Programming Part 1.pptx
Advance C# Programming Part 1.pptxAdvance C# Programming Part 1.pptx
Advance C# Programming Part 1.pptxpercivalfernandez3
 
Java Presentation For Syntax
Java Presentation For SyntaxJava Presentation For Syntax
Java Presentation For SyntaxPravinYalameli
 
Java Data Types
Java Data TypesJava Data Types
Java Data TypesSpotle.ai
 
Java Presentation
Java PresentationJava Presentation
Java Presentationpm2214
 
introduction to Python (for beginners)
introduction to Python (for beginners)introduction to Python (for beginners)
introduction to Python (for beginners)guobichrng
 
C# programming language
C# programming languageC# programming language
C# programming languageswarnapatil
 
Introduction to Basic Java Versions and their features
Introduction to Basic Java Versions and their featuresIntroduction to Basic Java Versions and their features
Introduction to Basic Java Versions and their featuresAkash Badone
 
Kotlin - A Programming Language
Kotlin - A Programming Language Kotlin - A Programming Language
Kotlin - A Programming Language Mobio Solutions
 
OOP Introduction with java programming language
OOP Introduction with java programming languageOOP Introduction with java programming language
OOP Introduction with java programming languageMd.Al-imran Roton
 
Introduction to java (revised)
Introduction to java (revised)Introduction to java (revised)
Introduction to java (revised)Sujit Majety
 

Tendances (20)

Swift Programming Language
Swift Programming LanguageSwift Programming Language
Swift Programming Language
 
Swift programming language
Swift programming languageSwift programming language
Swift programming language
 
A swift introduction to Swift
A swift introduction to SwiftA swift introduction to Swift
A swift introduction to Swift
 
Introduction to Object Oriented Programming
Introduction to Object Oriented ProgrammingIntroduction to Object Oriented Programming
Introduction to Object Oriented Programming
 
Basic iOS Training with SWIFT - Part 1
Basic iOS Training with SWIFT - Part 1Basic iOS Training with SWIFT - Part 1
Basic iOS Training with SWIFT - Part 1
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
 
Intro to UIKit • Made by Many
Intro to UIKit • Made by ManyIntro to UIKit • Made by Many
Intro to UIKit • Made by Many
 
Introduction to object oriented programming
Introduction to object oriented programmingIntroduction to object oriented programming
Introduction to object oriented programming
 
Advance C# Programming Part 1.pptx
Advance C# Programming Part 1.pptxAdvance C# Programming Part 1.pptx
Advance C# Programming Part 1.pptx
 
Java Presentation For Syntax
Java Presentation For SyntaxJava Presentation For Syntax
Java Presentation For Syntax
 
Java Data Types
Java Data TypesJava Data Types
Java Data Types
 
Java Presentation
Java PresentationJava Presentation
Java Presentation
 
introduction to Python (for beginners)
introduction to Python (for beginners)introduction to Python (for beginners)
introduction to Python (for beginners)
 
C# programming language
C# programming languageC# programming language
C# programming language
 
Introduction to Basic Java Versions and their features
Introduction to Basic Java Versions and their featuresIntroduction to Basic Java Versions and their features
Introduction to Basic Java Versions and their features
 
Kotlin - A Programming Language
Kotlin - A Programming Language Kotlin - A Programming Language
Kotlin - A Programming Language
 
Ruby
RubyRuby
Ruby
 
Python
PythonPython
Python
 
OOP Introduction with java programming language
OOP Introduction with java programming languageOOP Introduction with java programming language
OOP Introduction with java programming language
 
Introduction to java (revised)
Introduction to java (revised)Introduction to java (revised)
Introduction to java (revised)
 

Similaire à Swift Tutorial Part 1. The Complete Guide For Swift Programming Language

L2 C# Programming Comments, Keywords, Identifiers, Variables.pdf
L2 C# Programming Comments, Keywords, Identifiers, Variables.pdfL2 C# Programming Comments, Keywords, Identifiers, Variables.pdf
L2 C# Programming Comments, Keywords, Identifiers, Variables.pdfMMRF2
 
Presentation 2nd
Presentation 2ndPresentation 2nd
Presentation 2ndConnex
 
Programming in scala - 1
Programming in scala - 1Programming in scala - 1
Programming in scala - 1Mukesh Kumar
 
SWITCH-CASE, Lesson Computer Programming.pptx
SWITCH-CASE, Lesson Computer Programming.pptxSWITCH-CASE, Lesson Computer Programming.pptx
SWITCH-CASE, Lesson Computer Programming.pptxAlwinJamesPuracan
 
Lec-2- Ehsjdjkck. Jdkdbd djskrogramming.pdf
Lec-2- Ehsjdjkck. Jdkdbd djskrogramming.pdfLec-2- Ehsjdjkck. Jdkdbd djskrogramming.pdf
Lec-2- Ehsjdjkck. Jdkdbd djskrogramming.pdfRahulKumar342376
 
(4) cpp automatic arrays_pointers_c-strings
(4) cpp automatic arrays_pointers_c-strings(4) cpp automatic arrays_pointers_c-strings
(4) cpp automatic arrays_pointers_c-stringsNico Ludwig
 
(3) c sharp introduction_basics_part_ii
(3) c sharp introduction_basics_part_ii(3) c sharp introduction_basics_part_ii
(3) c sharp introduction_basics_part_iiNico Ludwig
 
Chapter 01 Introduction to Java by Tushar B Kute
Chapter 01 Introduction to Java by Tushar B KuteChapter 01 Introduction to Java by Tushar B Kute
Chapter 01 Introduction to Java by Tushar B KuteTushar B Kute
 
8 introduction to_java_script
8 introduction to_java_script8 introduction to_java_script
8 introduction to_java_scriptVijay Kalyan
 
IOS Swift language 2nd tutorial
IOS Swift language 2nd tutorialIOS Swift language 2nd tutorial
IOS Swift language 2nd tutorialHassan A-j
 
The swift programming language
The swift programming languageThe swift programming language
The swift programming languagePardeep Chaudhary
 
Introduction to Python Part-1
Introduction to Python Part-1Introduction to Python Part-1
Introduction to Python Part-1Devashish Kumar
 
Bt0067 c programming and data structures 1
Bt0067 c programming and data structures 1Bt0067 c programming and data structures 1
Bt0067 c programming and data structures 1Techglyphs
 
Airbnb Javascript Style Guide
Airbnb Javascript Style GuideAirbnb Javascript Style Guide
Airbnb Javascript Style GuideCreative Partners
 
QTP VB Script Trainings
QTP VB Script TrainingsQTP VB Script Trainings
QTP VB Script TrainingsAli Imran
 
2.Getting Started with C#.Net-(C#)
2.Getting Started with C#.Net-(C#)2.Getting Started with C#.Net-(C#)
2.Getting Started with C#.Net-(C#)Shoaib Ghachi
 

Similaire à Swift Tutorial Part 1. The Complete Guide For Swift Programming Language (20)

L2 C# Programming Comments, Keywords, Identifiers, Variables.pdf
L2 C# Programming Comments, Keywords, Identifiers, Variables.pdfL2 C# Programming Comments, Keywords, Identifiers, Variables.pdf
L2 C# Programming Comments, Keywords, Identifiers, Variables.pdf
 
Intro to Scala
 Intro to Scala Intro to Scala
Intro to Scala
 
22 Jop Oct 08
22 Jop Oct 0822 Jop Oct 08
22 Jop Oct 08
 
Presentation 2nd
Presentation 2ndPresentation 2nd
Presentation 2nd
 
Programming in scala - 1
Programming in scala - 1Programming in scala - 1
Programming in scala - 1
 
SWITCH-CASE, Lesson Computer Programming.pptx
SWITCH-CASE, Lesson Computer Programming.pptxSWITCH-CASE, Lesson Computer Programming.pptx
SWITCH-CASE, Lesson Computer Programming.pptx
 
Lec-2- Ehsjdjkck. Jdkdbd djskrogramming.pdf
Lec-2- Ehsjdjkck. Jdkdbd djskrogramming.pdfLec-2- Ehsjdjkck. Jdkdbd djskrogramming.pdf
Lec-2- Ehsjdjkck. Jdkdbd djskrogramming.pdf
 
(4) cpp automatic arrays_pointers_c-strings
(4) cpp automatic arrays_pointers_c-strings(4) cpp automatic arrays_pointers_c-strings
(4) cpp automatic arrays_pointers_c-strings
 
C#/.NET Little Pitfalls
C#/.NET Little PitfallsC#/.NET Little Pitfalls
C#/.NET Little Pitfalls
 
(3) c sharp introduction_basics_part_ii
(3) c sharp introduction_basics_part_ii(3) c sharp introduction_basics_part_ii
(3) c sharp introduction_basics_part_ii
 
Chapter 01 Introduction to Java by Tushar B Kute
Chapter 01 Introduction to Java by Tushar B KuteChapter 01 Introduction to Java by Tushar B Kute
Chapter 01 Introduction to Java by Tushar B Kute
 
8 introduction to_java_script
8 introduction to_java_script8 introduction to_java_script
8 introduction to_java_script
 
IOS Swift language 2nd tutorial
IOS Swift language 2nd tutorialIOS Swift language 2nd tutorial
IOS Swift language 2nd tutorial
 
The swift programming language
The swift programming languageThe swift programming language
The swift programming language
 
Introduction to Python Part-1
Introduction to Python Part-1Introduction to Python Part-1
Introduction to Python Part-1
 
Bt0067 c programming and data structures 1
Bt0067 c programming and data structures 1Bt0067 c programming and data structures 1
Bt0067 c programming and data structures 1
 
Airbnb Javascript Style Guide
Airbnb Javascript Style GuideAirbnb Javascript Style Guide
Airbnb Javascript Style Guide
 
QTP VB Script Trainings
QTP VB Script TrainingsQTP VB Script Trainings
QTP VB Script Trainings
 
Final requirement
Final requirementFinal requirement
Final requirement
 
2.Getting Started with C#.Net-(C#)
2.Getting Started with C#.Net-(C#)2.Getting Started with C#.Net-(C#)
2.Getting Started with C#.Net-(C#)
 

Dernier

Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceanilsa9823
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 

Dernier (20)

Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 

Swift Tutorial Part 1. The Complete Guide For Swift Programming Language

  • 1. By: Hossam Ghareeb hossam.ghareb@gmail.com Part 1 The Complete Guide For Programming Language
  • 2. Contents. ● About Swift ● Hello World! with playground ● Variables & Constants ● Printing Output ● Type Conversion ● If ● If with optionals ● Switch ● Switch With Ranges. ● Switch With Tuples. ● Switch With Value Binding ● Switch With "Where" ● Loops ● Functions ● Passing & Returning Functions ● Closures (Blocks) ● Arrays ● Dictionaries ● Enum
  • 3. About Swift ● Swift is a new scripting programming language for iOS and OS X apps. ● Swift is easy, flexible and funny. ● Unlike Objective-C, Swift is not C Compatible. Objective-C is a superset of C but Swift is not. ● Swift is readable like Objective-C and designed to be familiar to Objective-C developers. ● You don't have to write semicolons, but you must write it if you want to write multiple statements in single line. ● You can start writing apps with Swift language starting from Xcode 6. ● Swift doesn't require main function to start with.
  • 4. Hello World! As usual we will start with printing "Hello World" message. We will use something called playground to explore Swift language. It's an amazing tool to write and debug code without compile or run. Create or open an Xcode project and create new playground:
  • 5. Hello World! Use "NSLog" or "println" to print message to console. As you see in the right side you can see in real time the values of variables or console message.
  • 6. Variables & Constants. In Swift, use 'let' for constans and 'var' for variables. In constants you can't change the value of a constant after being initialized and you must set a value to it. Although you use 'var' or 'let' for variables, Swift is typed language. The type is written after ':' . You don't have to write the type of variable or constant because the compiler will infer it using its initial value. BUT if you didn't set an initial value or the initial value that you provided is not enough to determine the type, you have to explicitly type the variable or constants. Check examples:
  • 8. Variables & Constants. In Objective-C we used to use mutability, for example: NSArray and NSMutableArray or NSString and NSMutableString In Swift, when you use var, all objects will be mutable BUT when you use let, all objects will be immutable:
  • 9. Printing Output ● We introduced the new way to print output using println(). Its very similar to NSLog() but NSLog is slower, adds timestamp to output message and appear in device log. Println() appear in debugger log only. ● In Swift you can insert values of variables inside String using "()" a backslash with parentheses, check example:
  • 10. Type Conversion Swift is unlike other languages, it will not implicitly convert types of result of statements. Lets check example in Obj-C : In Swift you can't do this. You have to decide the type of result by explicitly converting it to Double or Integer. Check next example:
  • 11. Type Conversion Here we should convert any one of them so the two variables be in same type. Swift guarantees safety in your code and makes you decide the type of your result.
  • 12. If ● In Swift, you don't have to add parentheses around the condition. But you should use them in complex conditions. ● Curly braces { } are required around block of code after If or else. This also provide safety to your code.
  • 13. If ● Conditions must be Boolean, true or false. Thus, the next code will not work as it was working in Objective-C : As you see in Swift, you cannot check in variable directly like Objective-C.
  • 14. If With Optionals ● You can set the variable value as Optional to indicate that it may contain a value or nil. ● Write question mark "?" after the type of variable to mark it as Optional. ● Think of it like the "weak" property, it may point to an object or nil ● Use let with If to check the Optional value. If the optional value is nil, the conditional will be false. OtherWise, the it will be true and the value will be assigned to the constant of let Check example:
  • 16. Switch Switch works in Swift like many other languages but with some new features and small differences: ● It supports any kind of data, not only Integers. It checks for equality. ● Switch statement must be exhaustive. It means that you have to cover (add cases for) all possible values for your variable. If you can't provide case statement for each value, add a default statement to catch other values. ● When a case is matched in switch, the program exits from the switch case and doesn't continue checking next cases. Thus, you don't have to explicitly break out the switch at the end of each case. Check examples:
  • 18. Switch Cont. ● As we said, there is no fallthrough in switch statements and therefore break is not required. So code like this will not work in Swift: ● As you see, each case must contain at least one executable statement. ● Multiple matches for single case can be separated by commas and no need for fallthrough cases
  • 20. Switch With Ranges. ● In Swift you can use the range of values for checking in case statements. Ranges are identified with "..." in Swift :
  • 21. Switch With Tuples. Tuples are used to group multiple values in a single compound value. Each value can be in any type. Values can be with any number as you like: You can decompose the values of tuples with many ways as you will see in examples. Most of time, tuples are used to return multiple values from function. Also can be use to enumerate dictionary contents as (key, value). Check examples:
  • 22. Switch With Tuples. ● Decomposing: ● Use underscore "_" to ignore parts:
  • 23. Switch With Tuples. ● You can use element index to access tuple values. Also you can name the elements and access them by name: ● With dictionary:
  • 24. Switch With Tuples. Using tuples with functions:
  • 25. Switch With Tuples. Now we will see tuples with switch. We will use it in checking that a point is located inside a box in grid. Also we want to check if the point located on x-axis or y-axis. Here is the gird:
  • 27. Switch With Value Binding You can bind the values of variables in switch case statements to temporary constants to be used inside the case body:
  • 28. Switch With "Where" "Where" is used with case statement to add additional condition. Check these examples:
  • 29. Switch With "Where" Another example in using "Where":
  • 30. Loops ● Like other languages, you can use for and for-in loops without changes. But in Swift you don't have to write the parentheses. ● for-in loops can iterate any collection of data. Also It can be used with ranges
  • 31. Functions ● Functions are created using the keyword 'func'. ● Parentheses are required for functions that don't take params. ● In parameters you type the name and type of variable between ':' ● You can describe or name the local variables of function like Objective-C by writing the name before the local variable OR add '#' if the local variable is already an appropriate name. Check examples:
  • 32. Functions ● Using names for local variables
  • 33. Functions ● In Swift, params are considered as constants and you can't change them. ● To change local variables, copy the values to other variables OR tell Swift that this value is not constant by writing 'var' before the name:
  • 34. Functions ● To return values, you have to write the type of returned info after '()' and "->". Use tuples to return multiple values at once. ● In Swift, you can use default parameter values. BUT be aware that when you wanna use function with default-valued params, you must write the name of the argument when you wanna use it. Check examples:
  • 35. Functions ● Using default parameter value: ● Functions can take variable number of arguments using '...' :
  • 36. Passing & Returning Functions ● In Swift, functions are first class objects. Thus they can be passed around ● Every function has type like this: ● You can pass a function as parameter or return it as a result. Check examples:
  • 37. Passing & Returning Functions
  • 38. Closures ● Closures are very similar to blocks in C and Objective-C. ● Closures are first class type so it can be nested , returned and passed as parameter. (Same as blocks in Objective-C) ● Functions are special cases of closures. ● Closures are enclosed in curly braces { } , then write the function type (arguments) -> (return type), followed by in keyword that separate the closure header from the body.
  • 39. Closures ● Example #1, using map with an array. map returns an array with result of each item
  • 40. Closures ● Example #2 of using closure as completion handler when sending api request
  • 41. Closures ● Example #3, using the built-in "sorted" function to sort any collection based on a closure that will decide the compare result of any two items
  • 42. Arrays ● Arrays in Swift are typed. You have to choose the type of array, array of Integers, array of Strings,....etc. That's different from Objective-C where you can create array with items of any type. ● You can write the type of array between square brackets [ ] OR If you initialized it with data, Swift will infer the type of array implicitly. ● Arrays by default are mutable arrays, except if you defined it as constant using 'let' it will be immutable. ● Length of array can be know by .count property, and you can check if is it empty or not by .isEmpty property.
  • 43. Arrays ● Creating and initializing array is easy. Also you can create array with certain size and default value for items: ● For appending items, use 'append' method or "+=" :
  • 44. Arrays ● You can retrieve and update array using subscript syntax. You will get runtime error if you tried to access item out of bound.
  • 45. Arrays ● You can easily iterate over an array using 'for-in' , 'for' or by 'enumerate'. 'enumerate' gives you the item and its index during enumeration.
  • 46. Dictionaries ● Dictionary in Swift is similar to one in Objective-C but like Array, Dictionary is strongly typed, all keys must be in same type and all values must be in same type. ● Type of Dictionary is inferred by initial values or you have to write the type between square brackets [ KeyType, ValueType] ● Like Arrays, Dictionaries by default are mutable dictionaries, except if you defined it as constant using 'let' it will be immutable. ● Check examples :)
  • 48. Enum ● Enum is very popular concept if you have specific values of something. ● Enum is created by the keyword 'enum' and listing all possible cases after the keyword 'case'
  • 49. Enum ● Enum can be used easily in switch case but as we know that switch in Swift is exhaustive, you have to list all possible cases.
  • 50. Enum With Associated Values ● Enum values can be used with associated values. Lets explain with an example. Suppose you describe products in your project, each product has a barcode. Barcodes have 2 types (UPC, QRCode) ● UPC code can be represented by 4 Integers (4,88581,01497,3), and QR code can be represented by String ("ABCFFDF")
  • 51. Enum With Associated Values ● So we need to represent the barcode with two condition UPC and QR , each one has associated values to give full information.
  • 52. Enum With Raw Values ● For sure in some cases you need to define some constants in enum with their values. For example the power of monster has different values based on game level (easy = 50, medium = 60, hard = 80, very hard = 120) and these values are constant. So you need to make enum for power values and in same time save these values. You can create enum with cases values but they must be in same type and this type is written after enum name. Also you can use .rawValue to get the constant value. ● You can initialize an enum value using its constant value using this format EnumName(rawValue: value). It returns the enum that map to the given value. Be careful because the value returned is Optional, it may contain an enum or nil, BECAUSE Swift can guarantee that the given constant is exist in enum or not.
  • 53. Enum With Raw Values Example:
  • 54. Enum With Raw Values Example: ● Raw values can be Strings, Chars, Integers or floating point numbers. In using Integers as a type for raw values, if you set a value of any case, others auto_increment if you didn't specify values for them.
  • 55. Thanks We have finished Part 1. In next parts we will talk about Classes, Structures, OOP and some advanced features of Swift. If you liked the tutorial, please share and tweet with your friends. If you have any comments or questions, don't hesitate to email ME