Re: o Swift generics, y no can I haz u dispatch correctly?
Re: o Swift generics, y no can I haz u dispatch correctly?
- Subject: Re: o Swift generics, y no can I haz u dispatch correctly?
- From: Quincey Morris <email@hidden>
- Date: Sun, 27 Sep 2015 17:51:14 -0700
- Feedback-id: 167118m:167118agrif8a:167118sVa9viBNTa:SMTPCORP
On Sep 27, 2015, at 15:02 , has <email@hidden> wrote:
>
> The problem is, it all falls apart again when `AppData.unpack()` is called from another generic method:
>
> class Commands {
> func get<T>(v:Any) -> T {
> return d.unpack(v, returnType: T.self) as T
> }
> }
I think you’re falling foul of one of two things:
1. Swift has generics, not templates. They say. (I never know exactly what that means either, but I think it’s relevant here.) AFAIK, Swift won’t “carry” the original parameterized type through to other call sites and use it for further specialization. In the above example, T is unconstrained, so I don’t think it satisfies the stricter of the ‘unpack’ generic definitions, even though the type it happens to represent does.
2. Swift has known difficulties in choosing a more-specific specialization when some of the generic declarations have more than one type parameter, as your first ‘unpack’ does. I don’t know if this is a bug or a necessary limitation, but I have one bug report in about this and have seen other examples in the forums.
After playing around with it in a playground for a while, I found this solution:
> func unpack<T,U> (v: [U], type: [T].Type) -> [T] {
> return [0 as! T]
> }
>
> func unpack<T,U> (v: U, type: T.Type) -> T {
> return 0 as! T
> }
>
> func get<T,U> (v: U) -> T {
> return unpack (v, type: T.self)
> }
>
> func get<T,U> (v: [U]) -> [T] {
> return unpack (v, type: [T].self)
> }
>
> let a = get (1) as Int // produces 0
> let b = get ([2,3]) as [Int] // produces [0]
It ought to be simpler than this, but there’s still something going wrong with choosing the correct ‘get’ based on *just* the return types. I’m using the other input parameter to make this distinction, assuming that it’s an array if the result is an array, which may not be true in your case.
But maybe there’s something in this that helps you.
(P.S. If you want to ask questions like this, you could/should take them to the Swift forum in devforums. There are people who hang out there to whom this sort of thing is date night and red roses afterwards. Those are the people I think you need.)
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden