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?

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 88Mahmoud Samir Fayed
 
knapsackusingbranchandbound
knapsackusingbranchandboundknapsackusingbranchandbound
knapsackusingbranchandboundhodcsencet
 
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 SheetACASH1011
 
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 181Mahmoud 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 6eSAT Publishing House
 
Postgresql İndex on Expression
Postgresql İndex on ExpressionPostgresql İndex on Expression
Postgresql İndex on ExpressionMesut Ö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 RANGKAPSumarno Feriyal
 
Stata Programming Cheat Sheet
Stata Programming Cheat SheetStata Programming Cheat Sheet
Stata Programming Cheat SheetLaura Hughes
 
The Essence of the Iterator Pattern
The Essence of the Iterator PatternThe Essence of the Iterator Pattern
The Essence of the Iterator PatternEric Torreborre
 
Stata cheat sheet analysis
Stata cheat sheet analysisStata cheat sheet analysis
Stata cheat sheet analysisTim Essam
 
Stata cheat sheet: data processing
Stata cheat sheet: data processingStata cheat sheet: data processing
Stata cheat sheet: data processingTim 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 196Mahmoud 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.pptxAdrien Melquiond
 
Day 4a iteration and functions.pptx
Day 4a   iteration and functions.pptxDay 4a   iteration and functions.pptx
Day 4a iteration and functions.pptxAdrien 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
 

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

Programming for Mechanical Engineers in EES
Programming for Mechanical Engineers in EESProgramming for Mechanical Engineers in EES
Programming for Mechanical Engineers in EESNaveed 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.pdfenodani2008
 
Getting started with ES6
Getting started with ES6Getting started with ES6
Getting started with ES6Nitay Neeman
 
Test beautycleanness
Test beautycleannessTest beautycleanness
Test beautycleannessbergel
 
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 212Mahmoud Samir Fayed
 
Class & Object - User Defined Method
Class & Object - User Defined MethodClass & Object - User Defined Method
Class & Object - User Defined MethodPRN 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 185Mahmoud 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.pdfjeeteshmalani1
 
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 ReferenceSeung-Bum Lee
 
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.pdfmeejuhaszjasmynspe52
 
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.docxfaithxdunce63732
 
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.pptDeepVala5
 
Java programming lab manual
Java programming lab manualJava programming lab manual
Java programming lab manualsameer 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 196Mahmoud 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 88Mahmoud 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 {.pdfANJALIENTERPRISES1
 
11. session 11 functions and objects
11. session 11   functions and objects11. session 11   functions and objects
11. session 11 functions and objectsPhú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

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

Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxAshokKarra1
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONHumphrey A Beña
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management SystemChristalin Nelson
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptxmary850239
 
ClimART Action | eTwinning Project
ClimART Action    |    eTwinning ProjectClimART Action    |    eTwinning Project
ClimART Action | eTwinning Projectjordimapav
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfJemuel Francisco
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxVanesaIglesias10
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfTechSoup
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Mark Reed
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Celine George
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management systemChristalin Nelson
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptxmary850239
 
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxlancelewisportillo
 
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...JojoEDelaCruz
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxAnupkumar Sharma
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPCeline George
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfErwinPantujan2
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...Postal Advocate Inc.
 

Kürzlich hochgeladen (20)

Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptx
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management System
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx
 
ClimART Action | eTwinning Project
ClimART Action    |    eTwinning ProjectClimART Action    |    eTwinning Project
ClimART Action | eTwinning Project
 
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptxYOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptx
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)
 
INCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptx
INCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptxINCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptx
INCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptx
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management system
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx
 
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
 
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERP
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
 

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.