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

Weitere ähnliche Inhalte

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

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

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

Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.
MateoGardella
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 

Kürzlich hochgeladen (20)

Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.
 
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...
 
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
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.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
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
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
 

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.