Reputation: 2466
I'm trying to implement a custom flatMap
on a struct that has some generic items. The flatMap
would just Swift.flatMap
over the items using the provided transform function. The code here is a bit contrived, but it boggles my mind why the standard library version does not cause an error, but mine does.
Is there something I'm missing in my implementation of flatMap
?
struct Wrapper<T:NSObject> {
let items:[T]
func flatMap<U>(_ transform:(T) -> U?) -> Wrapper<U> {
let newItems = items.flatMap { transform($0) }
return Wrapper<U>(items: newItems)
}
}
protocol Something {}
let wrapper = Wrapper<UIView>(items: [UIView()])
// Using standard library flatMap
wrapper
.items
.flatMap { $0 as? Something } // ✅ No error
// ..
// Using custom flatMap
wrapper
.flatMap { $0 as? Something } // 🛑 ERROR: Generic parameter 'U' could not be inferred
// ..
Upvotes: 0
Views: 609
Reputation: 12109
Something
does not conform to NSObject
.
Swift 4 automatically infers constraints for the generic parameter U
used in your flatMap
function by looking at all parameters which include U
. U
is used as a generic parameter to Wrapper
which requires U: NSObject
. Something
is not a subclass of NSObject
.
The error message is just misleading.
Upvotes: 2