Swift: Associated types. Example.
Tags: swift, ios, mobile, programming
Published: 2023-02-04 07:42:55

The defined colors had to be available for both `UIColor` in UIKit and `Color` in SwiftUI. Obviously, we did not want to define all colors twice as that would be hard to maintain and result in a lot of duplicate code.

We already had a convenient way of defining colors using a custom convenience initializer on `UIColor` that takes a hexadecimal input:
```swift
let color = UIColor(hex: "FF7217")
```
We decided to reuse that method and define a protocol around it:
```swift
public protocol BrandColorSupporting {
    associatedtype ColorValue
    static func colorFor(hex: String, alpha: CGFloat) -> ColorValue
}
```
Some colors also required to be defined with a specific alpha value which we included in this protocol too. We then added support for this protocol for both `UIColor` and `Color`:
```swift
extension UIColor: BrandColorSupporting {
    public static func colorFor(hex: String, alpha: CGFloat) -> UIColor {
        return UIColor(hex: hex).withAlphaComponent(alpha)
    }
}

@available(iOS 13.0, *)
extension Color: BrandColorSupporting {
    public static func colorFor(hex: String, alpha: CGFloat) -> Color {
        return Color(UIColor.colorFor(hex: hex, alpha: alpha))
    }
}
```
As you can see, we reuse the logic of `UIColor` in our `Color` protocol adoption. This allowed us to reuse the convenience initializer of `UIColor` to create colors using a hexadecimal value.

As not all colors required to define an alpha component we added a default extension to our `BrandColorSupporting` protocol:
```swift
extension BrandColorSupporting {
    static func colorFor(hex: String) -> ColorValue {
        return colorFor(hex: hex, alpha: 1.0)
    }
}
```

## Defining static colors
Both `UIColor` and `Color` now conform to the `BrandColorSupporting` protocol which means that we can define extensions that become available to both.

We started defining colors:
```swift
public extension BrandColorSupporting {

    static var orangeCollectHero: ColorValue {
        colorFor(hex: "FF7217")
    }
}
```
The best thing of using associated types is that we can make use of the same logic while the result type is changed based on context:
```swift
let colorForSwiftUI: Color = Color.orangeCollectHero
let colorForUIKit: UIColor = UIColor.orangeCollectHero
```
As you can imagine this is a great way to work with brand colors.

---

Associated types in Swift Protocols.
[Declaration](https://dev.to/sergeyleschev/swift-associated-types-declaration-bp6)
[Example](https://dev.to/sergeyleschev/swift-associated-types-example-51ea)
[Contraints](https://dev.to/sergeyleschev/swift-associated-types-constraints-3aj6)
[Conforming a protocol to a protocol](https://dev.to/sergeyleschev/swift-conforming-a-protocol-to-a-protocol-pok)

---

**Contacts**
I have a clear focus on time-to-market and don't prioritize technical debt. And I took part in the Pre-Sale/RFX activity as a System Architect, assessment efforts for Mobile (iOS-Swift, Android-Kotlin), Frontend (React-TypeScript) and Backend (NodeJS-.NET-PHP-Kafka-SQL-NoSQL). And I also formed the work of Pre-Sale as a CTO from Opportunity to Proposal via knowledge transfer to Successful Delivery.

🛩️ #startups #management #cto #swift #typescript #database
📧 Email: sergey.leschev@gmail.com
👋 LinkedIn: https://linkedin.com/in/sergeyleschev/
👋 LeetCode: https://leetcode.com/sergeyleschev/
👋 Twitter: https://twitter.com/sergeyleschev
👋 Github: https://github.com/sergeyleschev
🌎 Website: https://sergeyleschev.github.io
🌎 Reddit: https://reddit.com/user/sergeyleschev
🌎 Quora: https://quora.com/sergey-leschev
🌎 Medium: https://medium.com/@sergeyleschev
🖨️ PDF Design Patterns: [Download](https://sergeyleschev.github.io/sergeyleschev-design-patterns.pdf)