On Jul 26, 2015, at 16:30 , Michael de Haan <m...@comcast.net> 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 (Cocoa-dev@lists.apple.com) 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: https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com