Generics Question
Generics Question
- Subject: Generics Question
- From: Michael de Haan <email@hidden>
- Date: Sun, 26 Jul 2015 15:10:34 -0700
I’m writing a coreData helper which will rely on Generics.
Could I get some input?
I have synthesized the problem down to this somewhat nonsensical code.
From Playground:
>>>>>>>>
func intFor(s:String) -> Int {
return Int(s)!
}
func genericIntFor<T>(s:String) -> T {
return T(s)! // T cannot be constructed because it has no accessible initializers.
}
let intFromStr = intFor("9”) // 9
let intFromStrB:Double = genericIntFor("9”)
<<<<<<<<<
The first function does pretty much what it says.
The second tries to use Generics, with an error as shown. Now, I **thought** ( which is often not a good thing) that T would allow , in this case, either an integer or double to be returned, given a valid string input that represents a number, say from 0 to 9.
Is it possible the way I wrote, or is there some fundamental misunderstanding of Generics? Thanks in advance.
_______________________________________________
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