• 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
Generics Question
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

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


  • Prev by Date: Re: NSPropertyListSerialization weirdness
  • Next by Date: Re: Generics Question
  • Previous by thread: Re: Updating a screensaver from 10.6 to 10.10
  • Next by thread: Re: Generics Question
  • Index(es):
    • Date
    • Thread