• 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: Marco S Hyman <email@hidden>
  • Date: Sun, 26 Jul 2015 16:43:31 -0700

> func genericFor<T>(s:String) -> T {
>
>    return T(s)!  // error. ’T’ cannot be constructed because it has no accessible initializers
> }

At compile time there is no way of determining if T has an initializer that
takes a string. You could do something like this

----------------

protocol InitFromString {
    init?(_ value: String)
}

func genericFor<T: InitFromString>(s:String) -> T {

   return T(s)!
}

----------------

Then add extensions to the various types you want to convert to make sure
they conform to the InitFromString protocol.


_______________________________________________

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


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: CGFloat and literal floats in Swift
  • Next by Date: Re: Generics Question
  • Previous by thread: Re: Generics Question
  • Next by thread: Re: Generics Question
  • Index(es):
    • Date
    • Thread