3

I have classes Alpha and Berry:

class Alpha { }
class Berry : Alpha { }

I have a function that using inheritance within it's generic:

func myFunc<T : Alpha>(v:T) -> T {
    return T()
}

I call myFunc like this:

myFunc(Berry())

In my project, the object that gets returned is of type Alpha, and not of type Berry. Is this is a bug in the compiler, or if this is simply something I'm misunderstanding about generics?

1 Answer 1

3

What you trying to achieve is passing an instance of Berry and getting another instance of Berry?

If so, following code should work:

class Alpha {

    required init() { } // ← YOU NEED THIS

    func printme() {
        println("I'm alpha")
    }
}
class Berry : Alpha {
    override func printme() {
        println("I'm berry")
    }
}

func myFunc<T:Alpha>(v:T) -> T {
    return v.dynamicType()
}
// This also works:
/*
func myFunc<T: Alpha>(v:T) -> T {
    return (T.self as T.Type)()
}
*/

let a = myFunc(Berry())
a.printme() // -> I'm berry

required init() { } is necessary to ensure all classes derived from Alpha have init() initializer. Here is related Q/A: Swift generics not preserving type

If what you want is passing Berry as a type and get new instance of Berry, try this:

class Alpha {
    required init() { }
    func printme() {
        println("alpha")
    }
}
class Berry : Alpha {
    override func printme() {
        println("berry")
    }
}

func myFunc<T:Alpha>(v:T.Type) -> T {
    return v()
}

let a = myFunc(Berry)
a.printme()
Sign up to request clarification or add additional context in comments.

2 Comments

Sweet, this just saved me hours of work around time. And it's more explicit and clean anyways.
"This also works:" It's not the same though. The first uses the runtime class of the object pointed to by v; whereas the second uses T, which is inferred at compile time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.