On 3 Sep 2015, at 8:55 AM, has <hengist.p...@virgin.net> wrote: > Stuck and looking for ideas here. I need to define a base class whose methods > vends instances of its subclasses (thus enabling chained method calls; your > basic query builder).
I’m assuming Swift 1.2. The following works in an OS X 10.10 playground: ////////////////////////////// class Factory: Printable { required init() {} class func makeNew() -> Self { return self() } var description: String { return "This is a Factory." } } class Product: Factory, Printable { override var description: String { return "This is a Product." } } let f = Factory.makeNew() // => __lldb_expr_580.Factory f.description // => "This is a Factory." let p = Product.makeNew() // => {__lldb_expr_580.Factory} p.description // => "This is a Product." ////////////////////////////// * Using an instance as a factory for its own class is contrary to general usage, so is a smell at best. It’s a job for a class func. (Yes, functional-programming operators do exactly that, but this is an example of the Factory pattern, not an operator. You shouldn’t have to instantiate a Product to make a Product.) * Explicitly calling init should be legitimate, as the changes to map{} and the like now allow you to use it in the closure. I could still imagine support for that usage being withdrawn. I’m not comfortable as a matter of style with making it Just Another Func — and the solution above makes it moot. * Self is the new instancetype. It takes care of casting issues. (I haven’t thought out all the corner cases, so don’t hit me. I wear glasses.) * I was confused by the REPL’s calling Product.makeNew() an {__lldb_expr_580.Factory}, but apparently the braces mean “some subclass of.” If anyone can offer an authoritative explanation, I’d be glad to know. * I assume the call to self() in makeNew() goes through to an initializer for Product, but my day job calls. — F _______________________________________________ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) 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: https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com