SlideShare ist ein Scribd-Unternehmen logo
1 von 25
Downloaden Sie, um offline zu lesen
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.

Weitere ähnliche Inhalte

Mehr von 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
 

Mehr von 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
 

Kürzlich hochgeladen

ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
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
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingTeacherCyreneCayanan
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docxPoojaSen20
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
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
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxVishalSingh1417
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfAyushMahapatra5
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxnegromaestrong
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
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
 

Kürzlich hochgeladen (20)

ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
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
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum 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
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
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
 

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.