Skip to content

With polymorphism, several descendant object/instance references can be assigned to a reference to the parent class, and yet the parent can exhibit the behavior of the descendant. In other words, you can declare a variable of a certain type (parent/UIControl) and it can store references of that type, but it can also store references to any child…

License

Notifications You must be signed in to change notification settings

iosbrain/OOP-Polymorphism-Playground

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 

Repository files navigation

OOP Polymorphism Playground

In this Xcode 8.2.1 playground built against the iOS 10 SDK, I used Swift 3 to demonstrate the object-oriented programming (OOP) characteristic of "polymorphism," which I've discussed extensively in the articles here and here.

Here I declare a variable of the UIControl type (parent) and assign it references to several subclasses (child classes of UIControl) like UITextField, UISlider, UISegmentedControl, and UIStepper. See how the parent can access properties and methods of its children -- or properties and methods common to parent and children. Here's an example:

var textField : UITextField = UITextField()
var slider : UISlider = UISlider()
var segmented : UISegmentedControl = UISegmentedControl()
var stepper: UIStepper = UIStepper()
 
var myControl : UIControl
 
myControl = textField
myControl.isHighlighted = true
print("I am a \(type(of: myControl)) now.")
 
myControl = slider
myControl.isEnabled = true
print("I am a \(type(of: myControl)) now.")
 
myControl = segmented
myControl.setNeedsLayout()
print("I am a \(type(of: myControl)) now.")
 
myControl = stepper
let insets = stepper.alignmentRectInsets
print("I am a \(type(of: myControl)) now.")

And here's the output from the playground code shown above:

I am a UITextField now.
I am a UISlider now.
I am a UISegmentedControl now.
I am a UIStepper now.

As shown above, several descendant object/instance references can be assigned to a reference to the parent class, and yet the parent can exhibit the behavior of the descendant.

Polymorphism enables you to develop general code that works with groups of related classes instead of developing code for each individual class.

Download this playground and start learning Swift and its OOP features! Thanks!

About

With polymorphism, several descendant object/instance references can be assigned to a reference to the parent class, and yet the parent can exhibit the behavior of the descendant. In other words, you can declare a variable of a certain type (parent/UIControl) and it can store references of that type, but it can also store references to any child…

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages