[swift-evolution] [Pitch] Improving unspecified generic usability
David Sweeris
davesweeris at mac.com
Tue Aug 8 08:52:42 CDT 2017
> On Aug 8, 2017, at 06:38, Karl Wagner <razielim at gmail.com> wrote:
>
>
>>> On 8. Aug 2017, at 04:35, David Sweeris via swift-evolution <swift-evolution at swift.org> wrote:
>>>
>>>
>>> On Aug 7, 2017, at 3:00 PM, Logan Shire via swift-evolution <swift-evolution at swift.org> wrote:
>>>
>>> One of my longstanding frustrations with generic types and protocols has been how hard it is to work with them when their type is unspecified.
>>> Often I find myself wishing that I could write a function that takes a generic type or protocol as a parameter, but doesn’t care what its generic type is.
>>>
>>> For example, if I have a type:
>>>
>>> struct Foo<T> {
>>> let name: String
>>> let value: T
>>> }
>>>
>>> or:
>>>
>>> protocol Foo {
>>> associatedtype T
>>> var name: String { get }
>>> var value: T { get }
>>> }
>>>
>>> And I want to write a function that only cares about Foo.name, I’d like to be able to:
>>>
>>> func sayHi(to foo: Foo) {
>>> print("hi \(foo.name)")
>>> }
>>>
>>> But instead I get the error, “Reference to generic type Foo requires arguments in <…>”
>>>
>>> Also, when you want to have a polymorphic array of generic types, you can’t:
>>>
>>> let foos: [Foo] = [Foo(name: "Int", value: 2), Foo(name: "Double", value: 2.0)]
>>>
>>> And if you remove the explicit type coercion, you just get [Any]
>>>
>>> let foos = [Foo(name: "Int", value: 2), Foo(name: "Double", value: 2.0)]
>>>
>>> I wish that could be inferred to be [Foo].
>>
>> What happens if you try to say "foos: [Foo<Any>] = ..."?
>>
>
> Foo<Int> and Foo<Any> are very different. Otherwise, you could take a Foo<Int>, cast it to a Foo<Any> and set a String as its value.
>
> I think what he means are partial generics, e.g: Foo<_>.
Oh I know, I just couldn't remember if it'd work as long as you didn't mess with the generic bits.
- Dave Sweeris
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170808/16341e9e/attachment.html>
More information about the swift-evolution
mailing list