SlideShare a Scribd company logo
1 of 25
Download to read offline
Unit 1—Lesson 2:
Constants, Variables, and Data Types
Constants and variables
Associate a name with a value

Defining a constant or variable

• Allocates storage for the value in memory

• Associate the constant name with the assigned value
Constants
Defined using the let keyword

let name = "John"
Defined using the let keyword

let pi = 3.14159
Can’t assign a constant a new value

let name = "John"
name = "James" Cannot assign to value: ‘name’ is a ‘let’ constant!
Variables
Defined using the var keyword

var age = 29
Can assign a new value to a variable

var age = 29
age = 30
let defaultScore = 100
var playerOneScore = defaultScore
var playerTwoScore = defaultScore
print(playerOneScore)
print(playerTwoScore)
playerOneScore = 200
print(playerOneScore)
100
100
200
Footnote here. If there is no footnote, delete this text box.
Starting location
Destination
Current location
Distance traveled
Remaining distance
Constant or variable?
Rules
Naming constants and variables
No mathematical symbols

No spaces

Can’t begin with a number



let π = 3.14159
let = 100
let 🎲 = 6
let mañana = "Tomorrow"
let anzahlDerBücher = 15 //numberOfBooks
Best practices
Naming constants and variables
1. Be clear and descriptive





2. Use camel case when multiple words in a name
✓⨯ n firstName
firstname firstName✓⨯
Comments
// Setting pi to a rough estimate
let π = 3.14
/* The digits of pi are infinite,
so instead I chose a close approximation.*/
let π = 3.14
Types
struct Person {
let firstName: String
let lastName: String
func sayHello() {
print("Hello there! My name is (firstName) (lastName).")
}
}
struct Person {
let firstName: String
let lastName: String
func sayHello() {
print("Hello there! My name is (firstName) (lastName).")
}
}
let aPerson = Person(firstName: "Jacob", lastName: "Edwards")
let anotherPerson = Person(firstName: "Candace", lastName: "Salinas")
aPerson.sayHello()
anotherPerson.sayHello()
Hello there! My name is Jacob Edwards.
Hello there! My name is Candace Salinas.
Most common types
Symbol Purpose Example
Integer Int Represents whole numbers 4
Double Double Represents numbers requiring decimal points 13.45
Boolean Bool Represents true or false values true
String String Represents text "Once upon a time…"
Type safety
let playerName = "Julian"
var playerScore = 1000
var gameOver = false
playerScore = playerName
var wholeNumber = 30
var numberWithDecimals = 17.5
wholeNumber = numberWithDecimals
Cannot assign value of type ‘String’ to type ‘Int’!
Cannot assign value of type ‘Double’ to type ‘Int’!
Type inference
let cityName = "San Francisco"
let pi = 3.1415927
Type annotation
let cityName: String = "San Francisco"
let pi: Double = 3.1415927
let number: Double = 3
print(number)
3.0
Three common cases
Type annotation
1. When you create a constant or variable before assigning it a value

let firstName: String
//...
firstName = "Layne"
Three common cases
Type annotation
2. When you create a constant or variable that could be inferred as two or more
different types

let middleInitial: Character = "J"
var remainingDistance: Float = 30
Three common cases
Type annotation
3. When you add properties to a type definition

struct Car {
let make: String
let model: String
let year: Int
}
Required values
var x Type annotation missing in pattern!
Required values
var x: Int
Required values
var x: Int
print(x) Variable 'x' used before being initialized!
Required values
var x: Int
x = 10
print(x)
10
Numeric literal formatting
var largeUglyNumber = 1000000000
var largePrettyNumber = 1_000_000_000
Lab: Constants and Variables.playground
Unit 1—Lesson 2
Open and complete the exercises in Lab - Constants and
Variables.playground
© 2017 Apple Inc. 

This work is licensed by Apple Inc. under the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International license.

More Related Content

More from SV.CO

Handout level-1-module-1
Handout   level-1-module-1Handout   level-1-module-1
Handout level-1-module-1SV.CO
 
Persistence And Documents
Persistence And DocumentsPersistence And Documents
Persistence And DocumentsSV.CO
 
Building complex input screens
Building complex input screensBuilding complex input screens
Building complex input screensSV.CO
 
Working with the Web: 
Decoding JSON
Working with the Web: 
Decoding JSONWorking with the Web: 
Decoding JSON
Working with the Web: 
Decoding JSONSV.CO
 
Saving Data
Saving DataSaving Data
Saving DataSV.CO
 
Alerts notification
Alerts notificationAlerts notification
Alerts notificationSV.CO
 
UI Dynamics
UI DynamicsUI Dynamics
UI DynamicsSV.CO
 
Practical animation
Practical animationPractical animation
Practical animationSV.CO
 
Segues and navigation controllers
Segues and navigation controllersSegues and navigation controllers
Segues and navigation controllersSV.CO
 
Camera And Email
Camera And EmailCamera And Email
Camera And EmailSV.CO
 
Scroll views
Scroll viewsScroll views
Scroll viewsSV.CO
 
Intermediate table views
Intermediate table viewsIntermediate table views
Intermediate table viewsSV.CO
 
Table views
Table viewsTable views
Table viewsSV.CO
 
Closures
ClosuresClosures
ClosuresSV.CO
 
Protocols
ProtocolsProtocols
ProtocolsSV.CO
 
App anatomy and life cycle
App anatomy and life cycleApp anatomy and life cycle
App anatomy and life cycleSV.CO
 
Extensions
ExtensionsExtensions
ExtensionsSV.CO
 
Gestures
GesturesGestures
GesturesSV.CO
 
View controller life cycle
View controller life cycleView controller life cycle
View controller life cycleSV.CO
 
Controls in action
Controls in actionControls in action
Controls in actionSV.CO
 

More from SV.CO (20)

Handout level-1-module-1
Handout   level-1-module-1Handout   level-1-module-1
Handout level-1-module-1
 
Persistence And Documents
Persistence And DocumentsPersistence And Documents
Persistence And Documents
 
Building complex input screens
Building complex input screensBuilding complex input screens
Building complex input screens
 
Working with the Web: 
Decoding JSON
Working with the Web: 
Decoding JSONWorking with the Web: 
Decoding JSON
Working with the Web: 
Decoding JSON
 
Saving Data
Saving DataSaving Data
Saving Data
 
Alerts notification
Alerts notificationAlerts notification
Alerts notification
 
UI Dynamics
UI DynamicsUI Dynamics
UI Dynamics
 
Practical animation
Practical animationPractical animation
Practical animation
 
Segues and navigation controllers
Segues and navigation controllersSegues and navigation controllers
Segues and navigation controllers
 
Camera And Email
Camera And EmailCamera And Email
Camera And Email
 
Scroll views
Scroll viewsScroll views
Scroll views
 
Intermediate table views
Intermediate table viewsIntermediate table views
Intermediate table views
 
Table views
Table viewsTable views
Table views
 
Closures
ClosuresClosures
Closures
 
Protocols
ProtocolsProtocols
Protocols
 
App anatomy and life cycle
App anatomy and life cycleApp anatomy and life cycle
App anatomy and life cycle
 
Extensions
ExtensionsExtensions
Extensions
 
Gestures
GesturesGestures
Gestures
 
View controller life cycle
View controller life cycleView controller life cycle
View controller life cycle
 
Controls in action
Controls in actionControls in action
Controls in action
 

Recently uploaded

Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...Pooja Nehwal
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
The byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxThe byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxShobhayan Kirtania
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...anjaliyadav012327
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 

Recently uploaded (20)

Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
The byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxThe byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptx
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 

Constants variables and data types

  • 1. Unit 1—Lesson 2: Constants, Variables, and Data Types
  • 2. Constants and variables Associate a name with a value Defining a constant or variable • Allocates storage for the value in memory • Associate the constant name with the assigned value
  • 3. Constants Defined using the let keyword let name = "John" Defined using the let keyword let pi = 3.14159 Can’t assign a constant a new value let name = "John" name = "James" Cannot assign to value: ‘name’ is a ‘let’ constant!
  • 4. Variables Defined using the var keyword var age = 29 Can assign a new value to a variable var age = 29 age = 30
  • 5. let defaultScore = 100 var playerOneScore = defaultScore var playerTwoScore = defaultScore print(playerOneScore) print(playerTwoScore) playerOneScore = 200 print(playerOneScore) 100 100 200
  • 6. Footnote here. If there is no footnote, delete this text box. Starting location Destination Current location Distance traveled Remaining distance Constant or variable?
  • 7. Rules Naming constants and variables No mathematical symbols No spaces Can’t begin with a number 
 let π = 3.14159 let = 100 let 🎲 = 6 let mañana = "Tomorrow" let anzahlDerBücher = 15 //numberOfBooks
  • 8. Best practices Naming constants and variables 1. Be clear and descriptive
 
 
 2. Use camel case when multiple words in a name ✓⨯ n firstName firstname firstName✓⨯
  • 9. Comments // Setting pi to a rough estimate let π = 3.14 /* The digits of pi are infinite, so instead I chose a close approximation.*/ let π = 3.14
  • 10. Types struct Person { let firstName: String let lastName: String func sayHello() { print("Hello there! My name is (firstName) (lastName).") } }
  • 11. struct Person { let firstName: String let lastName: String func sayHello() { print("Hello there! My name is (firstName) (lastName).") } } let aPerson = Person(firstName: "Jacob", lastName: "Edwards") let anotherPerson = Person(firstName: "Candace", lastName: "Salinas") aPerson.sayHello() anotherPerson.sayHello() Hello there! My name is Jacob Edwards. Hello there! My name is Candace Salinas.
  • 12. Most common types Symbol Purpose Example Integer Int Represents whole numbers 4 Double Double Represents numbers requiring decimal points 13.45 Boolean Bool Represents true or false values true String String Represents text "Once upon a time…"
  • 13. Type safety let playerName = "Julian" var playerScore = 1000 var gameOver = false playerScore = playerName var wholeNumber = 30 var numberWithDecimals = 17.5 wholeNumber = numberWithDecimals Cannot assign value of type ‘String’ to type ‘Int’! Cannot assign value of type ‘Double’ to type ‘Int’!
  • 14. Type inference let cityName = "San Francisco" let pi = 3.1415927
  • 15. Type annotation let cityName: String = "San Francisco" let pi: Double = 3.1415927 let number: Double = 3 print(number) 3.0
  • 16. Three common cases Type annotation 1. When you create a constant or variable before assigning it a value let firstName: String //... firstName = "Layne"
  • 17. Three common cases Type annotation 2. When you create a constant or variable that could be inferred as two or more different types let middleInitial: Character = "J" var remainingDistance: Float = 30
  • 18. Three common cases Type annotation 3. When you add properties to a type definition struct Car { let make: String let model: String let year: Int }
  • 19. Required values var x Type annotation missing in pattern!
  • 21. Required values var x: Int print(x) Variable 'x' used before being initialized!
  • 22. Required values var x: Int x = 10 print(x) 10
  • 23. Numeric literal formatting var largeUglyNumber = 1000000000 var largePrettyNumber = 1_000_000_000
  • 24. Lab: Constants and Variables.playground Unit 1—Lesson 2 Open and complete the exercises in Lab - Constants and Variables.playground
  • 25. © 2017 Apple Inc. This work is licensed by Apple Inc. under the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International license.