SlideShare a Scribd company logo
Unit 2—Lesson 3:
Structures
Structures
struct Person {
var name: String
}
Capitalize type names

Use lowercase for property names
Accessing property values
Structures
struct Person {
var name: String
}
let person = Person(name: "Jasmine")
print(person.name)
Jasmine
Adding functionality
Structures
struct Person {
var name: String
func sayHello() {
print("Hello there! My name is (name)!")
}
}
let person = Person(name: "Jasmine")
person.sayHello()
Hello there! My name is Jasmine!
Instances
struct Shirt {
var size: String
var color: String
}
let myShirt = Shirt(size: "XL", color: "blue")
let yourShirt = Shirt(size: "M", color: "red")
struct Car {
var make: String
var year: Int
var color: String
func startEngine() {...}
func drive() {...}
func park() {...}
func steer(direction: Direction) {...}
}
let firstCar = Car(make: "Honda", year: 2010, color: "blue")
let secondCar = Car(make: "Ford", year: 2013, color: "black")
firstCar.startEngine()
firstCar.drive()
Initializers
let string = String.init() // ""
let integer = Int.init() // 0
let bool = Bool.init() // false
Initializers
var string = String() // ""
var integer = Int() // 0
var bool = Bool() // false
Default values
Initializers
struct Odometer {
var count: Int = 0
}
let odometer = Odometer()
print(odometer.count)
0
Memberwise initializers
Initializers
let odometer = Odometer(count: 27000)
print(odometer.count)
27000
Memberwise initializers
Initializers
struct Person {
var name: String
}
Memberwise initializers
Initializers
struct Person {
var name: String
func sayHello() {
print("Hello there!")
}
}
let person = Person(name: "Jasmine") // Memberwise initializer
struct Shirt {
let size: String
let color: String
}
let myShirt = Shirt(size: "XL", color: "blue") // Memberwise initializer
struct Car {
let make: String
let year: Int
let color: String
}
let firstCar = Car(make: "Honda", year: 2010, color: "blue") // Memberwise initializer
Custom initializers
Initializers
struct Temperature {
var celsius: Double
}
let temperature = Temperature(celsius: 30.0)
let fahrenheitValue = 98.6
let celsiusValue = (fahrenheitValue - 32) / 1.8
let newTemperature = Temperature(celsius: celsiusValue)
struct Temperature {
var celsius: Double
init(celsius: Double) {
self.celsius = celsius
}
init(fahrenheit: Double) {
celsius = (fahrenheit - 32) / 1.8
}
}
let currentTemperature = Temperature(celsius: 18.5)
let boiling = Temperature(fahrenheit: 212.0)
print(currentTemperature.celsius)
print(boiling.celsius)
18.5
100.0
Lab: Structures
Unit 2—Lesson 3
Open and complete the following exercises in Lab -
Structures.playground:
• Exercise - Structs, Instances, and Default Values

• App Exercise - Workout Tracking
Instance methods
struct Size {
var width: Double
var height: Double
func area() -> Double {
return width * height
}
}
var someSize = Size(width: 10.0, height: 5.5)
let area = someSize.area() // Area is assigned a value of 55.0
Mutating methods
struct Odometer {
var count: Int = 0 // Assigns a default value to the 'count' property.
}
Need to

• Increment the mileage

• Reset the mileage
struct Odometer {
var count: Int = 0 // Assigns a default value to the 'count' property.
mutating func increment() {
count += 1
}
mutating func increment(by amount: Int) {
count += amount
}
mutating func reset() {
count = 0
}
}
var odometer = Odometer() // odometer.count defaults to 0
odometer.increment() // odometer.count is incremented to 1
odometer.increment(by: 15) // odometer.count is incremented to 16
odometer.reset() // odometer.count is reset to 0
Computed properties
struct Temperature {
let celsius: Double
let fahrenheit: Double
let kelvin: Double
}
let temperature = Temperature(celsius: 0, fahrenheit: 32, kelvin: 273.15)
struct Temperature {
var celsius: Double
var fahrenheit: Double
var kelvin: Double
init(celsius: Double) {
self.celsius = celsius
fahrenheit = celsius * 1.8 + 32
kelvin = celsius + 273.15
}
init(fahrenheit: Double) {
self.fahrenheit = fahrenheit
celsius = (fahrenheit - 32) / 1.8
kelvin = celsius + 273.15
}
init(kelvin: Double) {
self.kelvin = kelvin
celsius = kelvin - 273.15
fahrenheit = celsius * 1.8 + 32
}
}
let currentTemperature = Temperature(celsius: 18.5)
let boiling = Temperature(fahrenheit: 212.0)
let freezing = Temperature(kelvin: 273.15)
struct Temperature {
var celsius: Double
var fahrenheit: Double {
return celsius * 1.8 + 32
}
}
let currentTemperature = Temperature(celsius: 0.0)
print(currentTemperature.fahrenheit)
32.0
Add support for Kelvin
Challenge
Modify the following to allow the temperature to be read as Kelvin

struct Temperature {
let celsius: Double
var fahrenheit: Double {
return celsius * 1.8 + 32
}
}
Hint: Temperature in Kelvin is Celsius + 273.15
struct Temperature {
let celsius: Double
var fahrenheit: Double {
return celsius * 1.8 + 32
}
var kelvin: Double {
return celsius + 273.15
}
}
let currentTemperature = Temperature(celsius: 0.0)
print(currentTemperature.kelvin)
273.15
Property observers
struct StepCounter {
    var totalSteps: Int = 0 {
        willSet {
            print("About to set totalSteps to (newValue)")
        }
        didSet {
            if totalSteps > oldValue  {
                print("Added (totalSteps - oldValue) steps")
            }
        }
    }
}
Property observers
var stepCounter = StepCounter()
stepCounter.totalSteps = 40
stepCounter.totalSteps = 100
About to set totalSteps to 40
Added 40 steps
About to set totalSteps to 100
Added 60 steps
Type properties and methods
struct Temperature {
static var boilingPoint = 100.0
static func convertedFromFahrenheit(_ temperatureInFahrenheit: Double) -> Double {
return(((temperatureInFahrenheit - 32) * 5) / 9)
}
}
let boilingPoint = Temperature.boilingPoint
let currentTemperature = Temperature.convertedFromFahrenheit(99)
let positiveNumber = abs(-4.14)
Copying
var someSize = Size(width: 250, height: 1000)
var anotherSize = someSize
someSize.width = 500
print(someSize.width)
print(anotherSize.width)
500
250
self
struct Car {
var color: Color
var description: String {
return "This is a (self.color) car."
}
}
When not required
self
Not required when property or method names exist on the current object

struct Car {
var color: Color
var description: String {
return "This is a (color) car."
}
}
When required
self
struct Temperature {
var celsius: Double
init(celsius: Double) {
self.celsius = celsius
}
}
Lab: Structures
Unit 2—Lesson 3
Open and complete the remaining exercises in 

Lab - Structures.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

What's hot

The Ring programming language version 1.3 book - Part 44 of 88
The Ring programming language version 1.3 book - Part 44 of 88The Ring programming language version 1.3 book - Part 44 of 88
The Ring programming language version 1.3 book - Part 44 of 88
Mahmoud Samir Fayed
 
knapsackusingbranchandbound
knapsackusingbranchandboundknapsackusingbranchandbound
knapsackusingbranchandbound
hodcsencet
 
2016 SMU Research Day
2016 SMU Research Day2016 SMU Research Day
2016 SMU Research DayLiu Yang
 
Pandas Cheat Sheet
Pandas Cheat SheetPandas Cheat Sheet
Pandas Cheat Sheet
ACASH1011
 
The Ring programming language version 1.5.2 book - Part 22 of 181
The Ring programming language version 1.5.2 book - Part 22 of 181The Ring programming language version 1.5.2 book - Part 22 of 181
The Ring programming language version 1.5.2 book - Part 22 of 181
Mahmoud Samir Fayed
 
7.4 A arc length
7.4 A arc length7.4 A arc length
7.4 A arc lengthhartcher
 
Design of an automotive differential with reduction ratio greater than 6
Design of an automotive differential with reduction ratio greater than 6Design of an automotive differential with reduction ratio greater than 6
Design of an automotive differential with reduction ratio greater than 6
eSAT Publishing House
 
Postgresql index-expression
Postgresql index-expressionPostgresql index-expression
Postgresql İndex on Expression
Postgresql İndex on ExpressionPostgresql İndex on Expression
Postgresql İndex on Expression
Mesut Öncel
 
PERHITUNGAN TULANGAN LONGITUDINAL BALOK BETON BERTULANG RANGKAP
PERHITUNGAN TULANGAN LONGITUDINAL BALOK BETON BERTULANG RANGKAPPERHITUNGAN TULANGAN LONGITUDINAL BALOK BETON BERTULANG RANGKAP
PERHITUNGAN TULANGAN LONGITUDINAL BALOK BETON BERTULANG RANGKAP
Sumarno Feriyal
 
Stata Programming Cheat Sheet
Stata Programming Cheat SheetStata Programming Cheat Sheet
Stata Programming Cheat Sheet
Laura Hughes
 
The Essence of the Iterator Pattern
The Essence of the Iterator PatternThe Essence of the Iterator Pattern
The Essence of the Iterator Pattern
Eric Torreborre
 
Stata cheat sheet analysis
Stata cheat sheet analysisStata cheat sheet analysis
Stata cheat sheet analysis
Tim Essam
 
Stata cheat sheet: data processing
Stata cheat sheet: data processingStata cheat sheet: data processing
Stata cheat sheet: data processing
Tim Essam
 
The Ring programming language version 1.7 book - Part 71 of 196
The Ring programming language version 1.7 book - Part 71 of 196The Ring programming language version 1.7 book - Part 71 of 196
The Ring programming language version 1.7 book - Part 71 of 196
Mahmoud Samir Fayed
 
Day 4b iteration and functions for-loops.pptx
Day 4b   iteration and functions  for-loops.pptxDay 4b   iteration and functions  for-loops.pptx
Day 4b iteration and functions for-loops.pptx
Adrien Melquiond
 
Day 4a iteration and functions.pptx
Day 4a   iteration and functions.pptxDay 4a   iteration and functions.pptx
Day 4a iteration and functions.pptx
Adrien Melquiond
 
Q-learning and Deep Q Network (Reinforcement Learning)
Q-learning and Deep Q Network (Reinforcement Learning)Q-learning and Deep Q Network (Reinforcement Learning)
Q-learning and Deep Q Network (Reinforcement Learning)
Thom Lane
 

What's hot (19)

The Ring programming language version 1.3 book - Part 44 of 88
The Ring programming language version 1.3 book - Part 44 of 88The Ring programming language version 1.3 book - Part 44 of 88
The Ring programming language version 1.3 book - Part 44 of 88
 
knapsackusingbranchandbound
knapsackusingbranchandboundknapsackusingbranchandbound
knapsackusingbranchandbound
 
2016 SMU Research Day
2016 SMU Research Day2016 SMU Research Day
2016 SMU Research Day
 
Pandas Cheat Sheet
Pandas Cheat SheetPandas Cheat Sheet
Pandas Cheat Sheet
 
The Ring programming language version 1.5.2 book - Part 22 of 181
The Ring programming language version 1.5.2 book - Part 22 of 181The Ring programming language version 1.5.2 book - Part 22 of 181
The Ring programming language version 1.5.2 book - Part 22 of 181
 
7.4 A arc length
7.4 A arc length7.4 A arc length
7.4 A arc length
 
Design of an automotive differential with reduction ratio greater than 6
Design of an automotive differential with reduction ratio greater than 6Design of an automotive differential with reduction ratio greater than 6
Design of an automotive differential with reduction ratio greater than 6
 
Deflection and member deformation
Deflection and member deformationDeflection and member deformation
Deflection and member deformation
 
Postgresql index-expression
Postgresql index-expressionPostgresql index-expression
Postgresql index-expression
 
Postgresql İndex on Expression
Postgresql İndex on ExpressionPostgresql İndex on Expression
Postgresql İndex on Expression
 
PERHITUNGAN TULANGAN LONGITUDINAL BALOK BETON BERTULANG RANGKAP
PERHITUNGAN TULANGAN LONGITUDINAL BALOK BETON BERTULANG RANGKAPPERHITUNGAN TULANGAN LONGITUDINAL BALOK BETON BERTULANG RANGKAP
PERHITUNGAN TULANGAN LONGITUDINAL BALOK BETON BERTULANG RANGKAP
 
Stata Programming Cheat Sheet
Stata Programming Cheat SheetStata Programming Cheat Sheet
Stata Programming Cheat Sheet
 
The Essence of the Iterator Pattern
The Essence of the Iterator PatternThe Essence of the Iterator Pattern
The Essence of the Iterator Pattern
 
Stata cheat sheet analysis
Stata cheat sheet analysisStata cheat sheet analysis
Stata cheat sheet analysis
 
Stata cheat sheet: data processing
Stata cheat sheet: data processingStata cheat sheet: data processing
Stata cheat sheet: data processing
 
The Ring programming language version 1.7 book - Part 71 of 196
The Ring programming language version 1.7 book - Part 71 of 196The Ring programming language version 1.7 book - Part 71 of 196
The Ring programming language version 1.7 book - Part 71 of 196
 
Day 4b iteration and functions for-loops.pptx
Day 4b   iteration and functions  for-loops.pptxDay 4b   iteration and functions  for-loops.pptx
Day 4b iteration and functions for-loops.pptx
 
Day 4a iteration and functions.pptx
Day 4a   iteration and functions.pptxDay 4a   iteration and functions.pptx
Day 4a iteration and functions.pptx
 
Q-learning and Deep Q Network (Reinforcement Learning)
Q-learning and Deep Q Network (Reinforcement Learning)Q-learning and Deep Q Network (Reinforcement Learning)
Q-learning and Deep Q Network (Reinforcement Learning)
 

Similar to Structures

Programming for Mechanical Engineers in EES
Programming for Mechanical Engineers in EESProgramming for Mechanical Engineers in EES
Programming for Mechanical Engineers in EES
Naveed Rehman
 
exercises_for_live_coding_Java_advanced-2.pdf
exercises_for_live_coding_Java_advanced-2.pdfexercises_for_live_coding_Java_advanced-2.pdf
exercises_for_live_coding_Java_advanced-2.pdf
enodani2008
 
Getting started with ES6
Getting started with ES6Getting started with ES6
Getting started with ES6
Nitay Neeman
 
Module 4.pdf
Module 4.pdfModule 4.pdf
Module 4.pdf
VijayKumar886687
 
Test beautycleanness
Test beautycleannessTest beautycleanness
Test beautycleanness
bergel
 
The Ring programming language version 1.10 book - Part 43 of 212
The Ring programming language version 1.10 book - Part 43 of 212The Ring programming language version 1.10 book - Part 43 of 212
The Ring programming language version 1.10 book - Part 43 of 212
Mahmoud Samir Fayed
 
Class & Object - User Defined Method
Class & Object - User Defined MethodClass & Object - User Defined Method
Class & Object - User Defined Method
PRN USM
 
The Ring programming language version 1.5.4 book - Part 34 of 185
The Ring programming language version 1.5.4 book - Part 34 of 185The Ring programming language version 1.5.4 book - Part 34 of 185
The Ring programming language version 1.5.4 book - Part 34 of 185
Mahmoud Samir Fayed
 
1- Create a class called Point that has two instance variables, defi.pdf
1- Create a class called Point that has two instance variables, defi.pdf1- Create a class called Point that has two instance variables, defi.pdf
1- Create a class called Point that has two instance variables, defi.pdf
jeeteshmalani1
 
Chapter 6.6
Chapter 6.6Chapter 6.6
Chapter 6.6sotlsoc
 
Martin Fowler's Refactoring Techniques Quick Reference
Martin Fowler's Refactoring Techniques Quick ReferenceMartin Fowler's Refactoring Techniques Quick Reference
Martin Fowler's Refactoring Techniques Quick Reference
Seung-Bum Lee
 
130717666736980000
130717666736980000130717666736980000
130717666736980000
Tanzeel Ahmad
 
Produce a new version of k-means called MR-K-means(Multi-run K-mean.pdf
Produce a new version of k-means called MR-K-means(Multi-run K-mean.pdfProduce a new version of k-means called MR-K-means(Multi-run K-mean.pdf
Produce a new version of k-means called MR-K-means(Multi-run K-mean.pdf
meejuhaszjasmynspe52
 
CSC139 Chapter 10 Lab Assignment (2)PolymorphismObjectivesIn.docx
CSC139 Chapter 10 Lab Assignment (2)PolymorphismObjectivesIn.docxCSC139 Chapter 10 Lab Assignment (2)PolymorphismObjectivesIn.docx
CSC139 Chapter 10 Lab Assignment (2)PolymorphismObjectivesIn.docx
faithxdunce63732
 
Unit 1 Part - 3 constructor Overloading Static.ppt
Unit 1 Part - 3  constructor Overloading Static.pptUnit 1 Part - 3  constructor Overloading Static.ppt
Unit 1 Part - 3 constructor Overloading Static.ppt
DeepVala5
 
Java programming lab manual
Java programming lab manualJava programming lab manual
Java programming lab manual
sameer farooq
 
The Ring programming language version 1.7 book - Part 16 of 196
The Ring programming language version 1.7 book - Part 16 of 196The Ring programming language version 1.7 book - Part 16 of 196
The Ring programming language version 1.7 book - Part 16 of 196
Mahmoud Samir Fayed
 
The Ring programming language version 1.3 book - Part 83 of 88
The Ring programming language version 1.3 book - Part 83 of 88The Ring programming language version 1.3 book - Part 83 of 88
The Ring programming language version 1.3 book - Part 83 of 88
Mahmoud Samir Fayed
 
Circle.javaimport java.text.DecimalFormat;public class Circle {.pdf
Circle.javaimport java.text.DecimalFormat;public class Circle {.pdfCircle.javaimport java.text.DecimalFormat;public class Circle {.pdf
Circle.javaimport java.text.DecimalFormat;public class Circle {.pdf
ANJALIENTERPRISES1
 
11. session 11 functions and objects
11. session 11   functions and objects11. session 11   functions and objects
11. session 11 functions and objectsPhúc Đỗ
 

Similar to Structures (20)

Programming for Mechanical Engineers in EES
Programming for Mechanical Engineers in EESProgramming for Mechanical Engineers in EES
Programming for Mechanical Engineers in EES
 
exercises_for_live_coding_Java_advanced-2.pdf
exercises_for_live_coding_Java_advanced-2.pdfexercises_for_live_coding_Java_advanced-2.pdf
exercises_for_live_coding_Java_advanced-2.pdf
 
Getting started with ES6
Getting started with ES6Getting started with ES6
Getting started with ES6
 
Module 4.pdf
Module 4.pdfModule 4.pdf
Module 4.pdf
 
Test beautycleanness
Test beautycleannessTest beautycleanness
Test beautycleanness
 
The Ring programming language version 1.10 book - Part 43 of 212
The Ring programming language version 1.10 book - Part 43 of 212The Ring programming language version 1.10 book - Part 43 of 212
The Ring programming language version 1.10 book - Part 43 of 212
 
Class & Object - User Defined Method
Class & Object - User Defined MethodClass & Object - User Defined Method
Class & Object - User Defined Method
 
The Ring programming language version 1.5.4 book - Part 34 of 185
The Ring programming language version 1.5.4 book - Part 34 of 185The Ring programming language version 1.5.4 book - Part 34 of 185
The Ring programming language version 1.5.4 book - Part 34 of 185
 
1- Create a class called Point that has two instance variables, defi.pdf
1- Create a class called Point that has two instance variables, defi.pdf1- Create a class called Point that has two instance variables, defi.pdf
1- Create a class called Point that has two instance variables, defi.pdf
 
Chapter 6.6
Chapter 6.6Chapter 6.6
Chapter 6.6
 
Martin Fowler's Refactoring Techniques Quick Reference
Martin Fowler's Refactoring Techniques Quick ReferenceMartin Fowler's Refactoring Techniques Quick Reference
Martin Fowler's Refactoring Techniques Quick Reference
 
130717666736980000
130717666736980000130717666736980000
130717666736980000
 
Produce a new version of k-means called MR-K-means(Multi-run K-mean.pdf
Produce a new version of k-means called MR-K-means(Multi-run K-mean.pdfProduce a new version of k-means called MR-K-means(Multi-run K-mean.pdf
Produce a new version of k-means called MR-K-means(Multi-run K-mean.pdf
 
CSC139 Chapter 10 Lab Assignment (2)PolymorphismObjectivesIn.docx
CSC139 Chapter 10 Lab Assignment (2)PolymorphismObjectivesIn.docxCSC139 Chapter 10 Lab Assignment (2)PolymorphismObjectivesIn.docx
CSC139 Chapter 10 Lab Assignment (2)PolymorphismObjectivesIn.docx
 
Unit 1 Part - 3 constructor Overloading Static.ppt
Unit 1 Part - 3  constructor Overloading Static.pptUnit 1 Part - 3  constructor Overloading Static.ppt
Unit 1 Part - 3 constructor Overloading Static.ppt
 
Java programming lab manual
Java programming lab manualJava programming lab manual
Java programming lab manual
 
The Ring programming language version 1.7 book - Part 16 of 196
The Ring programming language version 1.7 book - Part 16 of 196The Ring programming language version 1.7 book - Part 16 of 196
The Ring programming language version 1.7 book - Part 16 of 196
 
The Ring programming language version 1.3 book - Part 83 of 88
The Ring programming language version 1.3 book - Part 83 of 88The Ring programming language version 1.3 book - Part 83 of 88
The Ring programming language version 1.3 book - Part 83 of 88
 
Circle.javaimport java.text.DecimalFormat;public class Circle {.pdf
Circle.javaimport java.text.DecimalFormat;public class Circle {.pdfCircle.javaimport java.text.DecimalFormat;public class Circle {.pdf
Circle.javaimport java.text.DecimalFormat;public class Circle {.pdf
 
11. session 11 functions and objects
11. session 11   functions and objects11. session 11   functions and objects
11. session 11 functions and objects
 

More from SV.CO

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

Francesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptxFrancesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptx
EduSkills OECD
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
TechSoup
 
678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf
CarlosHernanMontoyab2
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
MysoreMuleSoftMeetup
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
Vivekanand Anglo Vedic Academy
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
JosvitaDsouza2
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
Jean Carlos Nunes Paixão
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
Nguyen Thanh Tu Collection
 
Embracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic ImperativeEmbracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic Imperative
Peter Windle
 
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdfAdversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Po-Chuan Chen
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
Levi Shapiro
 
"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
SACHIN R KONDAGURI
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
Anna Sz.
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
EugeneSaldivar
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
RaedMohamed3
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
siemaillard
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
DeeptiGupta154
 
Honest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptxHonest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptx
timhan337
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
Ashokrao Mane college of Pharmacy Peth-Vadgaon
 

Recently uploaded (20)

Francesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptxFrancesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptx
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
 
678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
 
Embracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic ImperativeEmbracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic Imperative
 
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdfAdversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
 
"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
 
Honest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptxHonest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptx
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
 

Structures

  • 2. Structures struct Person { var name: String } Capitalize type names Use lowercase for property names
  • 3. Accessing property values Structures struct Person { var name: String } let person = Person(name: "Jasmine") print(person.name) Jasmine
  • 4. Adding functionality Structures struct Person { var name: String func sayHello() { print("Hello there! My name is (name)!") } } let person = Person(name: "Jasmine") person.sayHello() Hello there! My name is Jasmine!
  • 5. Instances struct Shirt { var size: String var color: String } let myShirt = Shirt(size: "XL", color: "blue") let yourShirt = Shirt(size: "M", color: "red")
  • 6. struct Car { var make: String var year: Int var color: String func startEngine() {...} func drive() {...} func park() {...} func steer(direction: Direction) {...} } let firstCar = Car(make: "Honda", year: 2010, color: "blue") let secondCar = Car(make: "Ford", year: 2013, color: "black") firstCar.startEngine() firstCar.drive()
  • 7. Initializers let string = String.init() // "" let integer = Int.init() // 0 let bool = Bool.init() // false
  • 8. Initializers var string = String() // "" var integer = Int() // 0 var bool = Bool() // false
  • 9. Default values Initializers struct Odometer { var count: Int = 0 } let odometer = Odometer() print(odometer.count) 0
  • 10. Memberwise initializers Initializers let odometer = Odometer(count: 27000) print(odometer.count) 27000
  • 12. Memberwise initializers Initializers struct Person { var name: String func sayHello() { print("Hello there!") } } let person = Person(name: "Jasmine") // Memberwise initializer
  • 13. struct Shirt { let size: String let color: String } let myShirt = Shirt(size: "XL", color: "blue") // Memberwise initializer struct Car { let make: String let year: Int let color: String } let firstCar = Car(make: "Honda", year: 2010, color: "blue") // Memberwise initializer
  • 14. Custom initializers Initializers struct Temperature { var celsius: Double } let temperature = Temperature(celsius: 30.0) let fahrenheitValue = 98.6 let celsiusValue = (fahrenheitValue - 32) / 1.8 let newTemperature = Temperature(celsius: celsiusValue)
  • 15. struct Temperature { var celsius: Double init(celsius: Double) { self.celsius = celsius } init(fahrenheit: Double) { celsius = (fahrenheit - 32) / 1.8 } } let currentTemperature = Temperature(celsius: 18.5) let boiling = Temperature(fahrenheit: 212.0) print(currentTemperature.celsius) print(boiling.celsius) 18.5 100.0
  • 16. Lab: Structures Unit 2—Lesson 3 Open and complete the following exercises in Lab - Structures.playground: • Exercise - Structs, Instances, and Default Values • App Exercise - Workout Tracking
  • 17. Instance methods struct Size { var width: Double var height: Double func area() -> Double { return width * height } } var someSize = Size(width: 10.0, height: 5.5) let area = someSize.area() // Area is assigned a value of 55.0
  • 18. Mutating methods struct Odometer { var count: Int = 0 // Assigns a default value to the 'count' property. } Need to • Increment the mileage • Reset the mileage
  • 19. struct Odometer { var count: Int = 0 // Assigns a default value to the 'count' property. mutating func increment() { count += 1 } mutating func increment(by amount: Int) { count += amount } mutating func reset() { count = 0 } } var odometer = Odometer() // odometer.count defaults to 0 odometer.increment() // odometer.count is incremented to 1 odometer.increment(by: 15) // odometer.count is incremented to 16 odometer.reset() // odometer.count is reset to 0
  • 20. Computed properties struct Temperature { let celsius: Double let fahrenheit: Double let kelvin: Double } let temperature = Temperature(celsius: 0, fahrenheit: 32, kelvin: 273.15)
  • 21. struct Temperature { var celsius: Double var fahrenheit: Double var kelvin: Double init(celsius: Double) { self.celsius = celsius fahrenheit = celsius * 1.8 + 32 kelvin = celsius + 273.15 } init(fahrenheit: Double) { self.fahrenheit = fahrenheit celsius = (fahrenheit - 32) / 1.8 kelvin = celsius + 273.15 } init(kelvin: Double) { self.kelvin = kelvin celsius = kelvin - 273.15 fahrenheit = celsius * 1.8 + 32 } } let currentTemperature = Temperature(celsius: 18.5) let boiling = Temperature(fahrenheit: 212.0) let freezing = Temperature(kelvin: 273.15)
  • 22. struct Temperature { var celsius: Double var fahrenheit: Double { return celsius * 1.8 + 32 } } let currentTemperature = Temperature(celsius: 0.0) print(currentTemperature.fahrenheit) 32.0
  • 23. Add support for Kelvin Challenge Modify the following to allow the temperature to be read as Kelvin struct Temperature { let celsius: Double var fahrenheit: Double { return celsius * 1.8 + 32 } } Hint: Temperature in Kelvin is Celsius + 273.15
  • 24. struct Temperature { let celsius: Double var fahrenheit: Double { return celsius * 1.8 + 32 } var kelvin: Double { return celsius + 273.15 } } let currentTemperature = Temperature(celsius: 0.0) print(currentTemperature.kelvin) 273.15
  • 25. Property observers struct StepCounter {     var totalSteps: Int = 0 {         willSet {             print("About to set totalSteps to (newValue)")         }         didSet {             if totalSteps > oldValue  {                 print("Added (totalSteps - oldValue) steps")             }         }     } }
  • 26. Property observers var stepCounter = StepCounter() stepCounter.totalSteps = 40 stepCounter.totalSteps = 100 About to set totalSteps to 40 Added 40 steps About to set totalSteps to 100 Added 60 steps
  • 27. Type properties and methods struct Temperature { static var boilingPoint = 100.0 static func convertedFromFahrenheit(_ temperatureInFahrenheit: Double) -> Double { return(((temperatureInFahrenheit - 32) * 5) / 9) } } let boilingPoint = Temperature.boilingPoint let currentTemperature = Temperature.convertedFromFahrenheit(99) let positiveNumber = abs(-4.14)
  • 28. Copying var someSize = Size(width: 250, height: 1000) var anotherSize = someSize someSize.width = 500 print(someSize.width) print(anotherSize.width) 500 250
  • 29. self struct Car { var color: Color var description: String { return "This is a (self.color) car." } }
  • 30. When not required self Not required when property or method names exist on the current object struct Car { var color: Color var description: String { return "This is a (color) car." } }
  • 31. When required self struct Temperature { var celsius: Double init(celsius: Double) { self.celsius = celsius } }
  • 32. Lab: Structures Unit 2—Lesson 3 Open and complete the remaining exercises in 
 Lab - Structures.playground
  • 33. © 2017 Apple Inc. This work is licensed by Apple Inc. under the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International license.