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.
Generic subscripts in 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.
Hashable key but only works if the key is a String. It stores integers in a dictionary.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 } } } }
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 } }
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.
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)
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.
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.