Protocol conform to other protocol with using where condition

i asked a question about it.

so I am copying the code from this link.

protocol MyCustomString {
    var inString: String { get }
}

extension Int: MyCustomString {
    var inString: String { String(self) }
}

extension Double: MyCustomString {
    var inString: String { String(self) }
}

extension String: MyCustomString {
    var inString: String { self }
}

make types to conform a protocol:

extension Collection where Element: MyCustomString, Self: MyCustomString {
    var inString: String {
        self.map(\.inString).joined(separator: ", ")
    }
}
// example
extension Array: MyCustomString where Element: MyCustomString {}
extension Set: MyCustomString where Element: MyCustomString {}

but this is annoying. So, I need to add each type I want to conform the protocol.
but why can't swift make type automatically conform to a protocol as long as satisfying with some conditions?

// error, extension of protocol 'Collection' cannot have an inheritance
extension Collection: MyCustomString where Element: MyCustomString {
    var inString: String {
        self.map{$0.inString}.joined(separator: ", ")
    }
}
1 Like
Terms of Service

Privacy Policy

Cookie Policy