Skip to content

Instantly share code, notes, and snippets.

@chakrit
Last active May 30, 2016 04:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chakrit/6a436054b37a7f80edc249b9f8eff8a1 to your computer and use it in GitHub Desktop.
Save chakrit/6a436054b37a7f80edc249b9f8eff8a1 to your computer and use it in GitHub Desktop.
In some circumstances where a lot of generics are involved, `make1` can returns a `Parent` instance instead of a `Child` instance.
import Foundation
protocol StringContainer {
var string: String { get }
init(string: String)
}
class Parent: NSObject, StringContainer {
var string: String
required init(string: String) {
self.string = string
}
}
class Child: Parent {
}
// Inferrence can fail here causing `T` to default back to Parent type.
func make1<T: StringContainer>(string: String, type: T.Type) -> T {
return T(string: string)
}
// More reliable
func make2<T: StringContainer>(string: String, type: T.Type) -> T {
return type.init(string: string)
}
dump(make1("bee", type: Child.self).string)
dump(make2("bee", type: Child.self).string)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment