> ## Documentation Index
> Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Swift Generic Type

A generic type in Swift is a custom class, structure, enumeration, or actor declared with one or more type parameters. These type parameters act as placeholders for concrete types that are specified at the time of instantiation, allowing the compiler to enforce strict type safety while maintaining type-agnostic implementations.

## Type Parameters

Type parameters are defined inside angle brackets (`< >`) immediately following the type's name. They are conventionally named using UpperCamelCase (e.g., `Element`, `T`, `Key`). Once defined, the type parameter can be used throughout the type's definition to declare properties, method parameters, and return types.

```swift theme={"dark"}
struct Container<Element> {
    var items: [Element]
    
    mutating func add(_ item: Element) {
        items.append(item)
    }
}
```

Multiple type parameters are separated by commas:

```swift theme={"dark"}
class Pair<T, U> {
    let first: T
    let second: U
    
    init(first: T, second: U) {
        self.first = first
        self.second = second
    }
}
```

## Type Constraints

By default, a type parameter can accept any concrete type. Type constraints restrict the allowed types by requiring the type parameter to inherit from a specific class or conform to a specific protocol (or protocol composition).

Constraints are applied directly in the type parameter list using the `:` syntax.

```swift theme={"dark"}
import UIKit

// 'Key' is constrained to types conforming to the 'Hashable' protocol
struct HashMap<Key: Hashable, Value> {
    var storage: [Key: Value] = [:]
}

// 'T' is constrained to inherit from 'UIViewController'
class ViewControllerWrapper<T: UIViewController> {
    let viewController: T
    
    init(viewController: T) {
        self.viewController = viewController
    }
}
```

## Generic Implementation and Specialization

When a generic type is instantiated, concrete types replace the type parameters. Unlike languages that strictly rely on monomorphization (generating distinct code for every type), Swift uses a hybrid approach to balance performance and binary size.

By default, Swift compiles a single shared implementation for a generic type. This shared code uses runtime type metadata and value witness tables to dynamically handle operations (like memory allocation, copying, and destruction) for different concrete types, which minimizes code bloat.

However, as a compiler optimization, Swift performs generic specialization (monomorphization) when the concrete types are statically knowable and visible to the optimizer. In these cases, the compiler generates highly optimized, distinct machine code for the specific concrete type, eliminating the runtime overhead of dynamic dispatch.

```swift theme={"dark"}
// Depending on visibility and optimization levels, the compiler may use the 
// shared generic implementation or generate specialized machine code for Int and String.
var intContainer = Container<Int>(items: [])
var stringContainer = Container<String>(items: [])
```

## Extending Generic Types

When extending a generic type, you do not provide the type parameter list in the extension declaration. The original type parameters from the type definition are implicitly available within the body of the extension.

```swift theme={"dark"}
extension Container {
    var topItem: Element? {
        return items.last
    }
}
```

### Conditional Extensions

You can use a generic `where` clause in an extension to add functionality only when the type parameters satisfy specific conditions. This allows a generic type to gain additional methods or properties based on the capabilities of its resolved concrete type.

```swift theme={"dark"}
// This method is only available if 'Element' conforms to 'Equatable'
extension Container where Element: Equatable {
    func contains(_ item: Element) -> Bool {
        return items.contains(item)
    }
}
```

## Generics in Protocols (Associated Types)

While classes, structs, enums, and actors use type parameters (`<T>`), Swift protocols handle generics differently to avoid complex type hierarchies. Protocols use `associatedtype` to declare a placeholder name for a type that is used as part of the protocol. The concrete type is determined by the conforming type.

```swift theme={"dark"}
protocol DataProvider {
    associatedtype DataType
    func fetch() -> DataType
}

struct StringProvider: DataProvider {
    // The compiler infers DataType == String based on the return type
    func fetch() -> String {
        return "Data"
    }
}
```

<div
  style={{ 
display: "flex", 
justifyContent: "space-between", 
alignItems: "center", 
maxWidth: "754px", 
padding: "1rem 0",
marginBottom: "24px"
}}
>
  <span style={{ fontWeight: "bold", fontSize: "1.25rem", color: "var(--tw-prose-headings)", fontFamily: "Inter, ui-sans-serif, system-ui, sans-serif" }}>Tired of Poor Swift Skills? Fix That With Deep Grasping!</span>

  <a
    href="https://syntblaze.com"
    target="_blank"
    style={{ 
  marginLeft: "24px",
  textDecoration: "none", 
  backgroundColor: "#007AFF",
  color: "#ffffff", 
  padding: "6px 16px", 
  borderRadius: "16px",
  fontSize: "0.9rem",
  fontWeight: "600",
  textAlign: "center",
  transition: "background-color 0.2s ease"
}}
  >
    Learn More
  </a>
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/skill-tracking.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=b9b0305c93bb501c9e767b5c76c88835" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/skill-tracking.png" />

  <img src="https://mintcdn.com/syntblazellc/23tyuOzaWS88qFlc/images/nuggets.png?fit=max&auto=format&n=23tyuOzaWS88qFlc&q=85&s=c86c80197299762989e9b882419b2109" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/nuggets.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/bite-sized-exercises.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=a65f9a38c37ff28ab73ed783c53c60e3" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/bite-sized-exercises.png" />
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap", marginTop: "12px" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/mastery-chain.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=748a1763454713e679260fbb95f154a2" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/mastery-chain.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-previews.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=242f61448ff5dd6deaaab2dccc13b507" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-previews.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-explanations.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=cf0fc1c31f9cd0fc26716781be05fbc9" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-explanations.png" />
</div>
