user965972
user965972

Reputation: 2597

swift generic function without parameters

How can I specify the subclass in this snippet? It's not returning anything so the compiler has nothing to infer the type. Neither can I call root.addSublayers(["a","b"]) without a compiler error.

possible function:

func addSublayers(names: [String]? = nil, ofSubType type:???)
func addSublayers<type: CALayer>(names: [String]? = nil)

body:

{
  for name in (names ?? defaultNames)
  {
     let layer = type() //init a custom subclass of CALayer
     layer.name = name
     self.addSubLayer(layer) 
  }
}

Upvotes: 0

Views: 461

Answers (2)

user965972
user965972

Reputation: 2597

In case anyone comes across this question, here is the pattern I am currently using.

func foo<T>(type: T.Type) {}
func bar<T>(type: T.Type = String.self) 
{
    foo(type:type)
}

This pattern is also used in the standard library.

Upvotes: 1

Lawgrin Foul
Lawgrin Foul

Reputation: 308

Try something like this:

func addSublayers<T: CALayer>(names: [String]? = nil, asdf : T)
{
    for name in names!
    {
        let layer = T() //init a custom subclass of CALayer
        layer.name = name
        self.addSubLayer(layer)
    }
}

or this

func addSublayers<T: CALayer>(names: [String]? = nil) ->T?
{
    for name in names!
    {
        let layer = T() //init a custom subclass of CALayer
        layer.name = name
        self.addSubLayer(layer)
    }
    return nil
}

Upvotes: 1

Related Questions