[Swift] Constraints for extensions on specific generics

Originator:zwaldowski
Number:rdar://21901489 Date Originated:20-Jul-2015 01:16 PM
Status:Open Resolved:false
Product:Developer Tools Product Version:Swift 2.0 (swiftlang-700.0.45)/Xcode 7.0 beta 3 (7A152u)
Classification:Enhancement Reproducible:Sometimes
 
Summary:
Constraints on protocol extensions in Swift 2.0 provide significant benefits for programming using protocols. As generics are conceptually related to protocols with associated types, it would make sense to be able to extend generic types in a similar way.

Consider the nascent Result/Either pattern. Beginning in Swift 2.0, there's really only one idiomatic implementation for such a type, and the community is bearing that out. Lots of functionality is built on top of that specific generic type; map, flatMap, and so on. Composition using the concrete Result type becomes very important.

But if I were to want to add my own functionality for certain use cases of Result — think of instance methods that unpacks types from an enum in a Result, like when parsing JSON or a property list — I would be unable to do that without wrapping Result in a new type, which logically makes that new type incompatible with anything using the original type. While a lot of this is mitigated with protocol extensions in Swift 2, the community does not seem to be embracing an EitherType. As well, type inference in closures becomes a lot harder if a flatMap on one EitherType can map to any other EitherType.

Steps to Reproduce:
1. Attempt to extend a generic type for specializations with a specific type
2. Compiler yells at you
3. Implement wrapper type 
4. Be forced to deal with reimplementing all the underlying types' functionality, other incompatibilities

Expected Results:
Extensions on generics can be constrained in parallel to protocols with associated types being constrained in extensions.

Actual Results:
Generics can only be extended for all specializations of the generic.

Version:
Swift version 2.0 (swiftlang-700.0.45 clang-700.0.57.2)/Version 7.0 beta 3 (7A152u)

Notes:
Discussion of desired patterns and samples included in attached playground.

Configuration:
N/A

Attachments:
'JSONResult.playground.zip' was successfully uploaded.

Duplicates

Number Status Originator Product Title
rdar://21901489 Closed zach Developer Tools [Swift] Constraints for extensions on specific generics

Comments

Attachment: https://drive.google.com/file/d/0B3FglI-wO7EqWDJQVUFtV3FfeTA/view

By zwaldowski at July 20, 2015, 5:17 p.m. (reply...)

Please note: Reports posted here will not necessarily be seen by Apple. All problems should be submitted at bugreport.apple.com before they are posted here. Please only post information for Radars that you have filed yourself, and please do not include Apple confidential information in your posts. Thank you!