Class Extension example in Swift

In this short Swift code example we will learn how to extend classes in Swift

  • Declare an object of String data type and extend it with our own custom function
  • Extend Int class with our own custom function
import UIKit

class ViewController: UIViewController {
    override func viewDidLoad() {
        // Declare String value
        let firstName:String = "Sergey"

        // Declare Int value
        let intNumber:Int=5
        // Call the "takeAway()" function we have extended the Int class with: 
        print("5 take away 4 equals \(intNumber.takeAway(4))")
        // Call the greatTheWorld() function we have extended the String class with

// Extend the String class in Swift
extension String {
    func greatTheWorld() {
         print("Hello world")

// Extend the Int class in Swift
extension Int {
    func takeAway(a:Int)->Int {
        return self-a;

Learn iOS Development with these Video Courses

How to Make a Freaking iPhone App - iOS 10 and Swift 3
icon icon

iOS 10 & Swift 3: From Beginner to Paid Professional

The Complete iOS 10 Developer Course - Build 21 Apps

Swift 3 - Learn to Code with Apple's New Language
icon icon

Learn How to Build Mobile Apps for iOS with Swift, PHP and MySQL
icon icon

Follow me on one of your favourite social networks to learn about new video tutorials and code examples:

Twitter: @SwiftVideoBlog
Google Plus:
Facebook: Swift Developer Blog on Facebook