0
0
Swiftprogramming~7 mins

Generic subscripts in Swift

Choose your learning style9 modes available
Introduction

Generic subscripts let you access parts of a type using flexible keys or indexes that can be different types. This helps write reusable and clear code.

When you want to access elements in a collection using different types of keys.
When you need a flexible way to get or set values in a custom data structure.
When you want to write code that works with many types without repeating yourself.
When you want to create a dictionary-like structure with custom key types.
When you want to simplify access to complex data using a single subscript interface.
Syntax
Swift
subscript<T>(key: T) -> ValueType {
    get {
        // return value for key
    }
    set {
        // set value for key
    }
}

The <T> after subscript means this subscript works with any type T.

You can define get and set blocks to read and write values.

Examples
This example shows a subscript that accepts any Hashable key but only works if the key is a String. It stores integers in a dictionary.
Swift
struct Box {
    var items = [String: Int]()

    subscript<T: Hashable>(key: T) -> Int? {
        get {
            if let key = key as? String {
                return items[key]
            }
            return nil
        }
        set {
            if let key = key as? String, let newValue = newValue {
                items[key] = newValue
            }
        }
    }
}
This subscript uses a generic index to return one of two values. It matches the index to 0 or 1 to decide which value to return.
Swift
struct Pair {
    var first: Int
    var second: Int

    subscript<T>(index: T) -> Int? {
        if let i = index as? Int {
            switch i {
            case 0:
                return first
            case 1:
                return second
            default:
                return nil
            }
        }
        return nil
    }
}
Sample Program

This program defines a struct with a generic subscript that accepts any key that can be turned into a string. It stores and retrieves integer values using those keys.

Swift
struct FlexibleStorage {
    private var data = [String: Int]()

    subscript<T: CustomStringConvertible>(key: T) -> Int? {
        get {
            let stringKey = key.description
            return data[stringKey]
        }
        set {
            let stringKey = key.description
            data[stringKey] = newValue
        }
    }
}

var storage = FlexibleStorage()
storage["apples"] = 10
storage[42] = 5
print(storage["apples"] ?? 0)
print(storage[42] ?? 0)
print(storage["oranges"] ?? 0)
OutputSuccess
Important Notes

Generic subscripts can make your code more flexible but can also make it harder to understand if overused.

Use constraints like Hashable or CustomStringConvertible to limit what types can be used as keys.

Remember to handle cases where the key type does not match expected types to avoid runtime errors.

Summary

Generic subscripts let you use different types as keys or indexes in one subscript.

They help write reusable and flexible code for custom data access.

Use type constraints and safe casting to keep your code clear and safe.