Swift 1.2b3: Function constraints don’t support subtype constraints between type parameters

Originator:rix.rob
Number:rdar://20158053 Date Originated:13-Mar-2015 05:00 PM
Status:Open Resolved:
Product:Developer Tools Product Version:Xcode-beta (6D543q)
Classification:Other Bug Reproducible:Always
 
Summary:
I have a function which finds or creates a value of some type from a value of some other type using a lens:

struct Lens<Whole, Part> {
	let from: Whole -> Part
	let to: (Part, Whole) -> Whole
}

func findOrCreate<C: CollectionType, From: Equatable>(collection: C, lens: Lens<From, C.Generator.Element>) -> Lens<From, C.Generator.Element> {
	return Lens(
		from: { value in find(collection) { lens($0, value) == value }.map { collection[$0] } ?? lens(value) },
		to: lens.to)
}

The use case is to find or construct a subview. However, subviews are of type NSView, not of the subclass used by `lens`; so subviews of other types should be ignored. Therefore, I want to change the test to consider only elements of the appropriate subtype of C.Generator.Element. This requires a new type parameter, To, and a subtype constraint To: C.Generator.Element. However, Swift rejects this constraint.


Steps to Reproduce:
1. Compile this:

struct Lens<Whole, Part> {
	let from: Whole -> Part
	let to: (Part, Whole) -> Whole
}

func findOrCreate<C: CollectionType, From: Equatable, To: C.Generator.Element>(collection: C, lens: Lens<From, To>) -> Lens<From, C.Generator.Element> {
	return Lens(
		from: { value in find(collection) { ($0 as? To).map { lens($0, value) == value } ?? false }.map { collection[$0] } ?? lens(value) },
		to: lens.to)
}



Expected Results:
I expected it to compile.


Actual Results:
It does not compile:
Desktop/subtype-constraint.swift:8:55: error: inheritance from non-protocol, non-class type 'C.Generator.Element'


Regression:
N/A


Notes:
I would have accepted that it might want me to constraint C.Generator.Element to AnyObject:

func findOrCreate<C: CollectionType, From: Equatable, To where C.Generator.Element: AnyObject, To: C.Generator.Element>(collection: C, lens: Lens<From, To>) -> Lens<From, C.Generator.Element>

but that doesn’t compile either:

Desktop/subtype-constraint.swift:8:58: error: type 'To' constrained to non-protocol type 'C.Generator.Element'

Comments

Duped as rdar://20163076

By heath.borders at March 14, 2015, 5:22 a.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!