[swift-users] A somewhat stupid question about protocol conformances
Adrian Zubarev
adrian.zubarev at devandartist.com
Sat Nov 25 02:11:39 CST 2017
This is correct. None of your types does conform to your protocol because you never conformance explicitly.
The extenstion you wrote is just a conditional extension which says if the Self type conforms to AreaProtocol and the associated typed Element is a CGPoint then add the area method to it. Nothing more, nothing less.
Now you may think that you have to rewrite that extension to `extension Sequence : AreaProtocol where Element == CGPoint`, but that won't work because retroactively conforming protocols to other protocols is not supported yet. Nor are conditional conformances included yet, but they will in Swift 4.1 or 5.
You have one option left.
protocol MySequence : Sequence, AreaProtocol where Element == CGPoint {}
extension Array : MySequence {}
Then also conform other sequences you need to support that functionality.
Double check if the code compiles, I wrote it on my iPhone, but you get the idea now.
--
Adrian Zubarev
Sent with Airmail
Am 25. November 2017 um 07:40:25, Antonino Ficarra via swift-users (swift-users at swift.org(mailto:swift-users at swift.org)) schrieb:
> In this code example:
>
> import Foundation
>
> protocol AreaProtocol {
> func area() -> CGFloat
>
> // implemented in protocol extension
> func volume( height:CGFloat ) -> CGFloat
> // ....
> }
>
> extension AreaProtocol {
> func volume( height:CGFloat ) -> CGFloat {
> return height * area()
> }
> // ....
> // ....
> }
>
>
> // conform CGPoint sequences to AreaProtocol
> extension Sequence
> where Self : AreaProtocol, Element == CGPoint
> {
> func area() -> CGFloat {
> return 0.0 // ... poligon area
> }
> }
>
> let p0 = CGPoint(x: 0.0, y: 0.0)
> let p1 = CGPoint(x: 2.0, y: 0.0)
> let p2 = CGPoint(x: 2.0, y: 2.0)
> let p3 = CGPoint(x: 0.0, y: 2.0)
>
> let poligon = [p0,p1,p2,p3]
> let a = poligon.area()// ! Type '[CGPoint]' does not conform to protocol 'AreaProtocol'
> let v = poligon.volume( height:10.0 )// ! Value of type '[CGPoint]' has no member 'volume'
>
>
> An array of CGPoint is a CGPoint sequence? Why the array don't gets automatic conformance to AreaProtocol?
> How can conform an array of CGPoint to AreaProtocol?
>
> Sorry for my bad english,
> Antonino
>
> _______________________________________________
> swift-users mailing list
> swift-users at swift.org
> https://lists.swift.org/mailman/listinfo/swift-users
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20171125/430e2a3c/attachment.html>
More information about the swift-users
mailing list