Chapters

Hide chapters

Swift Cookbook

Live Edition · Multiplatform · Swift · Editor agnostic

Use Extensions in Swift
Written by Team Kodeco

Extensions in Swift allow you to add new functionality to existing classes, structures, enumerations, or protocols. It allows you to add new methods, computed properties and initializers to a class without having to subclass it or make any modifications to the original source code.

Here’s an example of how to use an extension to add a new method to an existing class:

import Foundation

extension Double {
  func roundToDecimal(_ fractionDigits: Int) -> Double {
    let multiplier = pow(10, Double(fractionDigits))
    return Darwin.round(self * multiplier) / multiplier
  }
}

This creates an extension for the built-in Double class that adds a new method roundToDecimal which rounds the double value to a specified number of decimal places.

You can use this method on any Double value like this:

let myDouble = 3.14159265
print(myDouble.roundToDecimal(2))  // prints 3.14

Here’s an example of how to use an extension to add a new computed property to an existing struct:

extension CGSize {
  var area: CGFloat {
    return width * height
  }
}

This creates an extension for the built-in CGSize struct that adds a new computed property area which calculates the area of the size.

You can use this property on any CGSize value like this:

let mySize = CGSize(width: 2.0, height: 3.0)
print(mySize.area)  // prints 6.0
© 2024 Kodeco Inc.