Using protocol with associated type inside a generic function in Swift

773 views Asked by At

Hi I'm trying to create a function which accepts a generic type that conforms to a specific protocol, and this protocol has a static builder that return a new instance of the same class (using associated type), after that he returns the new object that was created.

The generic function will return a list of the generic type.

In my efforts to make it compile, I found a solution, but I feel like I cheated, please see the following code:

import UIKit

protocol SomeRougeProtocol {
    associatedtype U

    static func convert(id: String) -> U
}

class FirstRougeClass: SomeRougeProtocol {
    typealias U = FirstRougeClass

    let value: String

    init(value: String = "") {
        self.value = value
    }

    static func convert(id: String) -> FirstRougeClass {
        return FirstRougeClass(value: id)
    }
}

class SecondRougeClass: SomeRougeProtocol {
    typealias U = SecondRougeClass

    let value: String

    init(value: String = "") {
        self.value = "special \(value)"
    }

    static func convert(id: String) -> SecondRougeClass {
        return SecondRougeClass()
    }
}


/// Takes type and generate an array from it.
func superConvert<T: SomeRougeProtocol>(class: T) -> [T.U] {
    return [T.convert(id: "1"), T.convert(id: "2"), T.convert(id: "3")]
}

// *** This is the cheasty part, I have to create a disposable object to pass as input, it won't compile otherwise.
let disposableObject = FirstRougeClass()
let a: [FirstRougeClass] = superConvert(class: disposableObject)

a[0].value // Generates "1" in the playground, success!

My question is, if there is a better way to achieve what I done? without using a disposable object would be a big plus haha

Thanks!

0

There are 0 answers