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

Weitere ähnliche Inhalte

Was ist angesagt?

knapsackusingbranchandbound
knapsackusingbranchandboundknapsackusingbranchandbound
knapsackusingbranchandbound
hodcsencet
 
2016 SMU Research Day
2016 SMU Research Day2016 SMU Research Day
2016 SMU Research Day
Liu Yang
 
7.4 A arc length
7.4 A arc length7.4 A arc length
7.4 A arc length
hartcher
 

Was ist angesagt? (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)
 

Ähnlich wie Structures

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
 
Class & Object - User Defined Method
Class & Object - User Defined MethodClass & Object - User Defined Method
Class & Object - User Defined Method
PRN USM
 
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.6
sotlsoc
 
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
 
11. session 11 functions and objects
11. session 11   functions and objects11. session 11   functions and objects
11. session 11 functions and objects
Phúc Đỗ
 

Ähnlich wie 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
 

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

Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 
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
PECB
 
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
heathfieldcps1
 

Kürzlich hochgeladen (20)

Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
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
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
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
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
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
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
 
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
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
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
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room service
 
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
 

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.