Extensions in Swift

Syntax:

swift
extension SomeType {}

Usage:

To add new functionality to existing class, structure, enumerations.Extension can't override existing functionality.

Example:

To add colors as part of theming

Create color set within Assets folder and name it as ThemeColors.

For each color set within Assets folder, create a new static constant for color set

swift
import Foundation
import SwiftUI

extension Color {
    static let accent = Color("AccentColor")
    static let background = Color("BackgroundColor")
    static let success = Color("SuccessColor")
    static let failure = Color("FailureColor")
    static let secondaryText = Color("SecondaryTextColor")
}

To use our new colors we can now do so by:

swift
import SwiftUI

struct ContentView: View {
    var body: some View {
        ZStack {
            Color.background.ignoresSafeArea()
            VStack {
                Text("Accent Color").foregroundColor(Color.accentColor)
                Text("Secondary Text Color").foregroundColor(Color.secondary)
                Text("Success Color").foregroundColor(Color.success)
                Text("Failure Color").foregroundColor(Color.failure)
            }
        }
    }
}
References: