• Open Menu Close Menu
  • Apple
  • Shopping Bag
  • Apple
  • Mac
  • iPad
  • iPhone
  • Watch
  • TV
  • Music
  • Support
  • Search apple.com
  • Shopping Bag
 

Lists

Open Menu Close Menu
  • Terms and Conditions
  • Lists hosted on this site
  • Email the Postmaster
  • Tips for posting to public mailing lists
Re: Generics Question
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Generics Question


  • Subject: Re: Generics Question
  • From: Quincey Morris <email@hidden>
  • Date: Sun, 26 Jul 2015 23:44:29 +0000

On Jul 26, 2015, at 16:30 , Michael de Haan  <email@hidden> wrote:
>
> func genericFor<T>(s:String) -> T {
>
>    return T(s)!  // error. ’T’ cannot be constructed because it has no accessible initializers
> }


This *generic* definition asks for an invocation of ‘init (_ s: String)’ *for any type that satisfies the constraints on T*. Since there are no constraints, this is only compilable if every type has a keywordless String-parameter initializer, and that’s obviously not true.

If this were a template (like an Obj-C macro, sorta), then the compiler could take the actual type of T and see what initializers are available. But Swift generics don’t work that way.

To do literally what you’re asking for, you’d have to declare a new protocol P that contains the form of ‘init’ you want to use, then use protocol extensions to add conformance to P, then write your function like this:

	func genericFor<T: P> …

But it’s not clear that this is what you’re aiming at — your example doesn’t need any generic function at all. That’s why I was asking about a more realistic example of the problem you’re trying to solve.

_______________________________________________

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


  • Follow-Ups:
    • Re: Generics Question
      • From: Michael de Haan  <email@hidden>
References: 
 >Generics Question (From: Michael de Haan  <email@hidden>)
 >Re: Generics Question (From: Michael de Haan  <email@hidden>)
 >Re: Generics Question (From: Quincey Morris <email@hidden>)
 >Re: Generics Question (From: Michael de Haan  <email@hidden>)

  • Prev by Date: Re: Generics Question
  • Next by Date: Re: Generics Question
  • Previous by thread: Re: Generics Question
  • Next by thread: Re: Generics Question
  • Index(es):
    • Date
    • Thread