SlideShare a Scribd company logo
1 of 20
Download to read offline
Unit 2—Lesson 4:
Classes, Inheritance
class Person {
let name: String
init(name: String) {
self.name = name
}
func sayHello() {
print("Hello there!")
}
}
let person = Person(name: "Jasmine")
print(person.name)
person.sayHello()
Jasmine
Hello there!
Inheritance
Base class

Subclass

Superclass
Vehicle
TandemBicycle
Bicycle
Defining a base class
Inheritance
class Vehicle {
var currentSpeed = 0.0
var description: String {
return "traveling at (currentSpeed) miles per hour"
}
func makeNoise() {
// do nothing - an arbitrary vehicle doesn't necessarily make a noise
}
}
let someVehicle = Vehicle()
print("Vehicle: (someVehicle.description)")
Vehicle: traveling at 0.0 miles per hour
Create a subclass
Inheritance
class SomeSubclass: SomeSuperclass {
// subclass definition goes here
}
class Bicycle: Vehicle {
var hasBasket = false
}
Create a subclass
Inheritance
class Bicycle: Vehicle {
var hasBasket = false
}
let bicycle = Bicycle()
bicycle.hasBasket = true
bicycle.currentSpeed = 15.0
print("Bicycle: (bicycle.description)")
Bicycle: traveling at 15.0 miles per hour
Create a subclass
Inheritance
class Tandem: Bicycle {
var currentNumberOfPassengers = 0
}
Create a subclass
Inheritance
class Tandem: Bicycle {
var currentNumberOfPassengers = 0
}
let tandem = Tandem()
tandem.hasBasket = true
tandem.currentNumberOfPassengers = 2
tandem.currentSpeed = 22.0
print("Tandem: (tandem.description)")
Tandem: traveling at 22.0 miles per hour
Override methods and properties
Inheritance
class Train: Vehicle {
override func makeNoise() {
print("Choo Choo!")
}
}
let train = Train()
train.makeNoise()
Choo Choo!
Override methods and properties
Inheritance
class Car: Vehicle {
var gear = 1
override var description: String {
return super.description + " in gear (gear)"
}
}
Override methods and properties
Inheritance
class Car: Vehicle {
var gear = 1
override var description: String {
return super.description + " in gear (gear)"
}
}
let car = Car()
car.currentSpeed = 25.0
car.gear = 3
print("Car: (car.description)")
Car: traveling at 25.0 miles per hour in gear 3
Override initializer
Inheritance
class Person {
let name: String
init(name: String) {
self.name = name
}
}
class Student: Person {
var favoriteSubject: String
}
Class ‘Student’ has no initializers!
Override initializer
Inheritance
class Person {
let name: String
init(name: String) {
self.name = name
}
}
class Student: Person {
var favoriteSubject: String
init(name: String, favoriteSubject: String) {
self.favoriteSubject = favoriteSubject
super.init(name: name)
}
}
References
• When you create an instance of a class: 

- Swift returns the address of that instance 

- The returned address is assigned to the variable

• When you assign the address of an instance to multiple variables:

- Each variable contains the same address

- Update one instance, and all variables refer to the updated instance
class Person {
let name: String
var age: Int
init(name: String, age: Int) {
self.name = name
self.age = age
}
}
var jack = Person(name: "Jack", age: 24)
var myFriend = jack
jack.age += 1
print(jack.age)
print(myFriend.age)
25
25
struct Person {
let name: String
var age: Int
}
var jack = Person(name: "Jack", age: 24)
var myFriend = jack
jack.age += 1
print(jack.age)
print(myFriend.age)
25
24
Memberwise initializers
• Swift does not create memberwise initializers for classes

• Common practice is for developers to create their own for their defined classes
Class or structure?
• Start new types as structures

• Use a class: 

- When you’re working with a framework that uses classes 

- When you want to refer to the same instance of a type in multiple places

- When you want to model inheritance
Lab: Classes.playground
Unit 2, Lesson 4
Open and complete the exercises in Lab - Classes.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

Similar to Classes

Hello. Im currently working on the last section to my assignment a.pdf
Hello. Im currently working on the last section to my assignment a.pdfHello. Im currently working on the last section to my assignment a.pdf
Hello. Im currently working on the last section to my assignment a.pdf
irshadkumar3
 
Intro to scala
Intro to scalaIntro to scala
Intro to scala
Joe Zulli
 

Similar to Classes (20)

Java oops PPT
Java oops PPTJava oops PPT
Java oops PPT
 
Python Lecture 13
Python Lecture 13Python Lecture 13
Python Lecture 13
 
02-OOP with Java.ppt
02-OOP with Java.ppt02-OOP with Java.ppt
02-OOP with Java.ppt
 
Forbidden Fruit: A Taste of Ruby's ParseTree
Forbidden Fruit: A Taste of Ruby's ParseTreeForbidden Fruit: A Taste of Ruby's ParseTree
Forbidden Fruit: A Taste of Ruby's ParseTree
 
11slide
11slide11slide
11slide
 
1.1 motivation
1.1 motivation1.1 motivation
1.1 motivation
 
Scala Quick Introduction
Scala Quick IntroductionScala Quick Introduction
Scala Quick Introduction
 
Intro toswift1
Intro toswift1Intro toswift1
Intro toswift1
 
Java Basic day-2
Java Basic day-2Java Basic day-2
Java Basic day-2
 
‫Chapter3 inheritance
‫Chapter3 inheritance‫Chapter3 inheritance
‫Chapter3 inheritance
 
Unit3 part1-class
Unit3 part1-classUnit3 part1-class
Unit3 part1-class
 
Hello. Im currently working on the last section to my assignment a.pdf
Hello. Im currently working on the last section to my assignment a.pdfHello. Im currently working on the last section to my assignment a.pdf
Hello. Im currently working on the last section to my assignment a.pdf
 
Intro to scala
Intro to scalaIntro to scala
Intro to scala
 
Scala uma poderosa linguagem para a jvm
Scala   uma poderosa linguagem para a jvmScala   uma poderosa linguagem para a jvm
Scala uma poderosa linguagem para a jvm
 
Oop scala
Oop scalaOop scala
Oop scala
 
Groovy Ast Transformations (greach)
Groovy Ast Transformations (greach)Groovy Ast Transformations (greach)
Groovy Ast Transformations (greach)
 
Hello Swift Final 5/5 - Structures and Classes
Hello Swift Final 5/5 - Structures and ClassesHello Swift Final 5/5 - Structures and Classes
Hello Swift Final 5/5 - Structures and Classes
 
11slide.ppt
11slide.ppt11slide.ppt
11slide.ppt
 
constructer.pptx
constructer.pptxconstructer.pptx
constructer.pptx
 
Scala for Java Developers (Silicon Valley Code Camp 13)
Scala for Java Developers (Silicon Valley Code Camp 13)Scala for Java Developers (Silicon Valley Code Camp 13)
Scala for Java Developers (Silicon Valley Code Camp 13)
 

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

The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
ZurliaSoop
 

Recently uploaded (20)

Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 

Classes

  • 2. class Person { let name: String init(name: String) { self.name = name } func sayHello() { print("Hello there!") } } let person = Person(name: "Jasmine") print(person.name) person.sayHello() Jasmine Hello there!
  • 4. Defining a base class Inheritance class Vehicle { var currentSpeed = 0.0 var description: String { return "traveling at (currentSpeed) miles per hour" } func makeNoise() { // do nothing - an arbitrary vehicle doesn't necessarily make a noise } } let someVehicle = Vehicle() print("Vehicle: (someVehicle.description)") Vehicle: traveling at 0.0 miles per hour
  • 5. Create a subclass Inheritance class SomeSubclass: SomeSuperclass { // subclass definition goes here } class Bicycle: Vehicle { var hasBasket = false }
  • 6. Create a subclass Inheritance class Bicycle: Vehicle { var hasBasket = false } let bicycle = Bicycle() bicycle.hasBasket = true bicycle.currentSpeed = 15.0 print("Bicycle: (bicycle.description)") Bicycle: traveling at 15.0 miles per hour
  • 7. Create a subclass Inheritance class Tandem: Bicycle { var currentNumberOfPassengers = 0 }
  • 8. Create a subclass Inheritance class Tandem: Bicycle { var currentNumberOfPassengers = 0 } let tandem = Tandem() tandem.hasBasket = true tandem.currentNumberOfPassengers = 2 tandem.currentSpeed = 22.0 print("Tandem: (tandem.description)") Tandem: traveling at 22.0 miles per hour
  • 9. Override methods and properties Inheritance class Train: Vehicle { override func makeNoise() { print("Choo Choo!") } } let train = Train() train.makeNoise() Choo Choo!
  • 10. Override methods and properties Inheritance class Car: Vehicle { var gear = 1 override var description: String { return super.description + " in gear (gear)" } }
  • 11. Override methods and properties Inheritance class Car: Vehicle { var gear = 1 override var description: String { return super.description + " in gear (gear)" } } let car = Car() car.currentSpeed = 25.0 car.gear = 3 print("Car: (car.description)") Car: traveling at 25.0 miles per hour in gear 3
  • 12. Override initializer Inheritance class Person { let name: String init(name: String) { self.name = name } } class Student: Person { var favoriteSubject: String } Class ‘Student’ has no initializers!
  • 13. Override initializer Inheritance class Person { let name: String init(name: String) { self.name = name } } class Student: Person { var favoriteSubject: String init(name: String, favoriteSubject: String) { self.favoriteSubject = favoriteSubject super.init(name: name) } }
  • 14. References • When you create an instance of a class: - Swift returns the address of that instance - The returned address is assigned to the variable • When you assign the address of an instance to multiple variables: - Each variable contains the same address - Update one instance, and all variables refer to the updated instance
  • 15. class Person { let name: String var age: Int init(name: String, age: Int) { self.name = name self.age = age } } var jack = Person(name: "Jack", age: 24) var myFriend = jack jack.age += 1 print(jack.age) print(myFriend.age) 25 25
  • 16. struct Person { let name: String var age: Int } var jack = Person(name: "Jack", age: 24) var myFriend = jack jack.age += 1 print(jack.age) print(myFriend.age) 25 24
  • 17. Memberwise initializers • Swift does not create memberwise initializers for classes • Common practice is for developers to create their own for their defined classes
  • 18. Class or structure? • Start new types as structures • Use a class: - When you’re working with a framework that uses classes - When you want to refer to the same instance of a type in multiple places - When you want to model inheritance
  • 19. Lab: Classes.playground Unit 2, Lesson 4 Open and complete the exercises in Lab - Classes.playground
  • 20. © 2017 Apple Inc. This work is licensed by Apple Inc. under the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International license.