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 (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

Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
EADTU
 
SURVEY I created for uni project research
SURVEY I created for uni project researchSURVEY I created for uni project research
SURVEY I created for uni project research
CaitlinCummins3
 
Personalisation of Education by AI and Big Data - Lourdes Guàrdia
Personalisation of Education by AI and Big Data - Lourdes GuàrdiaPersonalisation of Education by AI and Big Data - Lourdes Guàrdia
Personalisation of Education by AI and Big Data - Lourdes Guàrdia
EADTU
 

Kürzlich hochgeladen (20)

How to Send Pro Forma Invoice to Your Customers in Odoo 17
How to Send Pro Forma Invoice to Your Customers in Odoo 17How to Send Pro Forma Invoice to Your Customers in Odoo 17
How to Send Pro Forma Invoice to Your Customers in Odoo 17
 
Pharmaceutical Biotechnology VI semester.pdf
Pharmaceutical Biotechnology VI semester.pdfPharmaceutical Biotechnology VI semester.pdf
Pharmaceutical Biotechnology VI semester.pdf
 
ESSENTIAL of (CS/IT/IS) class 07 (Networks)
ESSENTIAL of (CS/IT/IS) class 07 (Networks)ESSENTIAL of (CS/IT/IS) class 07 (Networks)
ESSENTIAL of (CS/IT/IS) class 07 (Networks)
 
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
 
SURVEY I created for uni project research
SURVEY I created for uni project researchSURVEY I created for uni project research
SURVEY I created for uni project research
 
OS-operating systems- ch05 (CPU Scheduling) ...
OS-operating systems- ch05 (CPU Scheduling) ...OS-operating systems- ch05 (CPU Scheduling) ...
OS-operating systems- ch05 (CPU Scheduling) ...
 
Mattingly "AI and Prompt Design: LLMs with NER"
Mattingly "AI and Prompt Design: LLMs with NER"Mattingly "AI and Prompt Design: LLMs with NER"
Mattingly "AI and Prompt Design: LLMs with NER"
 
How to Manage Website in Odoo 17 Studio App.pptx
How to Manage Website in Odoo 17 Studio App.pptxHow to Manage Website in Odoo 17 Studio App.pptx
How to Manage Website in Odoo 17 Studio App.pptx
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
VAMOS CUIDAR DO NOSSO PLANETA! .
VAMOS CUIDAR DO NOSSO PLANETA!                    .VAMOS CUIDAR DO NOSSO PLANETA!                    .
VAMOS CUIDAR DO NOSSO PLANETA! .
 
An overview of the various scriptures in Hinduism
An overview of the various scriptures in HinduismAn overview of the various scriptures in Hinduism
An overview of the various scriptures in Hinduism
 
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
 
diagnosting testing bsc 2nd sem.pptx....
diagnosting testing bsc 2nd sem.pptx....diagnosting testing bsc 2nd sem.pptx....
diagnosting testing bsc 2nd sem.pptx....
 
e-Sealing at EADTU by Kamakshi Rajagopal
e-Sealing at EADTU by Kamakshi Rajagopale-Sealing at EADTU by Kamakshi Rajagopal
e-Sealing at EADTU by Kamakshi Rajagopal
 
Trauma-Informed Leadership - Five Practical Principles
Trauma-Informed Leadership - Five Practical PrinciplesTrauma-Informed Leadership - Five Practical Principles
Trauma-Informed Leadership - Five Practical Principles
 
OSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsOSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & Systems
 
When Quality Assurance Meets Innovation in Higher Education - Report launch w...
When Quality Assurance Meets Innovation in Higher Education - Report launch w...When Quality Assurance Meets Innovation in Higher Education - Report launch w...
When Quality Assurance Meets Innovation in Higher Education - Report launch w...
 
Model Attribute _rec_name in the Odoo 17
Model Attribute _rec_name in the Odoo 17Model Attribute _rec_name in the Odoo 17
Model Attribute _rec_name in the Odoo 17
 
Analyzing and resolving a communication crisis in Dhaka textiles LTD.pptx
Analyzing and resolving a communication crisis in Dhaka textiles LTD.pptxAnalyzing and resolving a communication crisis in Dhaka textiles LTD.pptx
Analyzing and resolving a communication crisis in Dhaka textiles LTD.pptx
 
Personalisation of Education by AI and Big Data - Lourdes Guàrdia
Personalisation of Education by AI and Big Data - Lourdes GuàrdiaPersonalisation of Education by AI and Big Data - Lourdes Guàrdia
Personalisation of Education by AI and Big Data - Lourdes Guàrdia
 

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.