robnik
June 15, 2022, 1:17am
1
There's no way to do something like this, correct?
protocol NodePathProtocol { ... }
typealias IDNodePath = [UUID]
typealias IntNodePath = [Int]
extension IntNodePath: NodePathProtocol { ... }
extension IDNodePath: NodePathProtocol { ... }
I guess I'll just change the code to make my types structs, like:
struct IntNodePath {
val path: [Int]
}
mayoff
(Rob Mayoff)
June 15, 2022, 4:48am
3
A different workaround is to add a separate protocol for the array elements, and a conditional conformance on Array
that uses the element-specific protocol:
import Foundation
protocol NodePathProtocol {
var components: [String] { get }
}
protocol NodePathArrayElementProtocol {
static func nodePathComponents(for array: [Self]) -> [String]
}
extension Array: NodePathProtocol where Element: NodePathArrayElementProtocol {
var components: [String] { Element.nodePathComponents(for: self) }
}
extension Int: NodePathArrayElementProtocol {
static func nodePathComponents(for array: [Int]) -> [String] {
return array.map { String($0) }
}
}
extension UUID: NodePathArrayElementProtocol {
static func nodePathComponents(for array: [UUID]) -> [String] {
return array.map { $0.uuidString }
}
}
Such use case could possibly be enabled with [Pitch] Extensions on bound generic types .
And you still cannot conforming Array
to the same protocol by such declarations. Instead, you may conditionally conform different concrete types specialized with Array
to the protocol.