SlideShare a Scribd company logo
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

Java tutorial for Beginners and Entry Level
Java tutorial for Beginners and Entry LevelJava tutorial for Beginners and Entry Level
Java tutorial for Beginners and Entry Level
Ramrao Desai
 
Java oops PPT
Java oops PPTJava oops PPT
Java oops PPT
kishu0005
 
Python Lecture 13
Python Lecture 13Python Lecture 13
Python Lecture 13
Inzamam Baig
 
02-OOP with Java.ppt
02-OOP with Java.ppt02-OOP with Java.ppt
02-OOP with Java.ppt
EmanAsem4
 
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
err
 
11slide
11slide11slide
11slide
IIUM
 
Scala Quick Introduction
Scala Quick IntroductionScala Quick Introduction
Scala Quick Introduction
Damian Jureczko
 
‫Chapter3 inheritance
‫Chapter3 inheritance‫Chapter3 inheritance
‫Chapter3 inheritance
Mahmoud Alfarra
 
Unit3 part1-class
Unit3 part1-classUnit3 part1-class
Unit3 part1-class
DevaKumari Vijay
 
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 scalaJoe Zulli
 
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
Isaias Barroso
 
Groovy Ast Transformations (greach)
Groovy Ast Transformations (greach)Groovy Ast Transformations (greach)
Groovy Ast Transformations (greach)
HamletDRC
 
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
Cody Yun
 
11slide.ppt
11slide.ppt11slide.ppt
11slide.ppt
MohammedNouh7
 
constructer.pptx
constructer.pptxconstructer.pptx
constructer.pptx
Nagaraju Pamarthi
 

Similar to Classes (20)

Java tutorial for Beginners and Entry Level
Java tutorial for Beginners and Entry LevelJava tutorial for Beginners and Entry Level
Java tutorial for Beginners and Entry Level
 
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
 

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

Embracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic ImperativeEmbracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic Imperative
Peter Windle
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
Vikramjit Singh
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
Delapenabediema
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
Sandy Millin
 
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
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
DhatriParmar
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
Jisc
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
GeoBlogs
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
heathfieldcps1
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
RaedMohamed3
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
BhavyaRajput3
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
Thiyagu K
 
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
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
Jisc
 
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
 
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
 
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
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
vaibhavrinwa19
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Thiyagu K
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
MIRIAMSALINAS13
 

Recently uploaded (20)

Embracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic ImperativeEmbracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic Imperative
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
 
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
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
 
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
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
 
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
 
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
 
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
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
 

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.