[Proposal] Factory Initializers

There are several reasons. It is a very common pattern in ObjC/Cocoa. For example, they allow class clusters (and the protocol equivalent).

I don’t see that as a strong argument for factory initializers.
The only benefit from factory initializer vs the convenient initializers in Obj-C is that they avoid an autorelease access. Now that ARC let us bypass the autorelease pool completely for such call, they are not needed anymore and implementing a factory initializer using a class method is far less error prone.

One of the Apple foundation people replied earlier in this thread that it would allow them to remove several hacks from the foundation overlays, and improve safety.

One of the ideas I am most excited about is the ability for a protocol to provide default conformances. For example, I have an Expression protocol to represent mathematical expressions, and I have a few basic conforming structs representing constants, variables, and some basic operations. With a factory method, I can say ‘Expression(2)’ or ‘Expression(“VarName”)’ and have it create the correct conformance. My conforming structs can even be private, if I want this to be the only way they are created.

If I have expensive-to-create immutable objects where I am creating equivalent values all the time, I can store commonly created values in a cache and return the cached versions (instead of creating an instance). I believe cocoa used to do this with NSNumbers before tagged pointers became a thing.

Or, I could return something which is lazily created.

Longer term (once reflection has improved), I have a proposal to allow extensible factory methods. We talked about it during the original discussion, but the gist is that there would be way to get a list of all types conforming to a protocol (or all subclasses of a class) from the compiler, and then you could use static methods to query those types until you found one which has the properties you are looking for, and then instantiate and return it. The end result is that you have a factory initializer where new conformances (even from plug-ins) can participate and be returned when appropriate. This proposal is a necessary first step to that.

As a concrete use-case of that extension, I have been experimenting for years with auto-creating UI to edit structured data (e.g. JSON or Plists) or objects. This is fairly easy in ObjC, but it is only possible in Swift in a very limited way at the moment. With the above extension and key paths, I should be able to recreate my ObjC interfaces in a nicer/swiftier way.

Those are just a few of the uses.

All your point are valid use cases, but they don’t tell us why is it better to support them using a language specific construct vs using a class method (and make the designated constructor private if you want to force all user of your class to use your factory method).

Or maybe I’m missing something ?

···

Le 21 mars 2017 à 22:09, Jonathan Hull via swift-evolution <swift-evolution@swift.org> a écrit :

Is this proposal in the pipeline for Swift 4?

···

On 1 April 2017 at 12:03, Adrian Zubarev via swift-evolution < swift-evolution@swift.org> wrote:

First, you should fix the indent in the code samples. Second, remove any
access modifier from inside a protocol. Third, we don’t support default
implementations directly inside protocols yet, so that’s a not valid
example.

Now my personal concerns. As far as I can tell XIB files in an iOS Project
are meant for UIViewControllers in first place, but it’s a common case that
they are also used to create reusable UIViews. The downside of that abusage
is view hierarchy clustering. Most developer creating a view of Self in
Self, which smells to me like really bad code.

MyCustomView // This view is useless
   + MyCustomView
       + CustomSubview1
   + CustomSubview1 // This is probably a dead IBOutlet

In fact Xcode does not use the initializer from NSCoding to show a live
rendered view inside interface builder, instead it will call a UIViews
designated initializer init(frame:). That results that a lot of the
developer write similar code like in the following snippet:

// This pattern results in a similar view cluster like mentioned above

class MyCustomView : UIView {
    override init(frame: CGRect) {
        let view = loadSomehowFromNib()
        self.addSubview(view)
    }
}

To solve this problem we’d need some functionality of factory
initializers. I believe as proposed the factory initializer won’t solve
that problem, because everything would be still restricted to a special
initializer annotated with factory.

Personally I would want to write something like this instead.

class MyCustomView : UIView {

    override init(frame: CGRect) {

        // Instantiating from a Nib file will call `init(coder:​)` on MyCustomView
        self = loadSomehowFromNib() // assuming () -> MyCustomView

        //
        self.frame = frame
    }
}

This should resolve the clustering issue by assigning the returned
instance from the function to self and create a correct view hierarchy.

+ MyCustomView
       + CustomSubview1

--
Adrian Zubarev
Sent with Airmail

Am 17. März 2017 um 17:26:29, Riley Testut via swift-evolution (
swift-evolution@swift.org) schrieb:

Hi again everyone!

Now that Swift 4 Stage 2 proposals are being considered, I thought it
might be time to revisit this proposal and see if it might align with the
goals set forth for Swift 4.

As a quick tl;dr, this proposal describes a new "factory initializer" that
would allow you to return a value from an initializer. This would have
several benefits, as mentioned in the proposal itself as well as throughout
this mailing list. For convenience, here's a link to the proposal on
GitHub: GitHub - rileytestut/swift-evolution: This maintains proposals for changes and user-visible enhancements to the Swift Programming Language.
blob/master/proposals/NNNN-factory-initializers.md

Would love to hear any more comments on this proposal, and if we feel this
is appropriate for considering for Swift 4 I'll happily re-open the pull
request!

Riley Testut

On Nov 19, 2016, at 7:45 AM, arkadi daniyelian <arkdan@icloud.com> wrote:

i would appreciate this feature.

For unexperienced developers, its often hard to recognize *when* factory
is a good fit to do the job, and how exactly approach the implementation. I
imagine having this feature built into the language may help to choose and
implement factory when its the right thing to do.

On Nov 18, 2016, at 12:23 AM, Charles Srstka via swift-evolution < > swift-evolution@swift.org> wrote:

Is there any chance of reviving this? It seems to me that since this would
require Swift initializers to be implemented internally in such a way that
they can return a value (as Objective-C init methods do), it may affect ABI
stability and thus may be germane to the current stage of Swift 4
development.

Charles

On Dec 17, 2015, at 3:41 PM, Riley Testut via swift-evolution < > swift-evolution@swift.org> wrote:

Recently, I proposed the idea of adding the ability to implement the
"class cluster" pattern from Cocoa (Touch) in Swift. However, as we
discussed it and came up with different approaches, it evolved into a
functionality that I believe is far more beneficial to Swift, and
subsequently should be the focus of its own proposal. So here is the
improved (pre-)proposal:

# Factory Initializers

The "factory" pattern is common in many languages, including Objective-C.
Essentially, instead of initializing a type directly, a method is called
that returns an instance of the appropriate type determined by the input
parameters. Functionally this works well, but ultimately it forces the
client of the API to remember to call the factory method instead, rather
than the type's initializer. This might seem like a minor gripe, but given
that we want Swift to be as approachable as possible to new developers, I
think we can do better in this regard.

Rather than have a separate factory method, I propose we build the factory
pattern right into Swift, by way of specialized “factory initializers”. The
exact syntax was proposed by Philippe Hausler from the previous thread, and
I think it is an excellent solution:

class AbstractBase {

public factory init(type: InformationToSwitchOn) {

     return ConcreteImplementation(type)

}

}

class ConcreteImplementation : AbstractBase {

}

Why exactly would this be useful in practice? In my own development, I’ve
come across a few places where this would especially be relevant:

## Class Cluster/Abstract Classes

This was the reasoning behind the original proposal, and I still think it
would be a very valid use case. The public superclass would declare all the
public methods, and could delegate off the specific implementations to the
private subclasses. Alternatively, this method could be used as an easy way
to handle backwards-compatibility: rather than litter the code with
branches depending on the OS version, simply return the OS-appropriate
subclass from the factory initializer. Very useful.

## Protocol Initializers

Proposed by Brent Royal-Gordon, we could use factory initializers with
protocol extensions to return the appropriate instance conforming to a
protocol for the given needs. Similar to the class cluster/abstract class
method, but can work with structs too. This would be closer to the factory
method pattern, since you don’t need to know exactly what type is returned,
just the protocol it conforms to.

## Initializing Storyboard-backed View Controller

This is more specific to Apple Frameworks, but having factory initializers
could definitely help here. Currently, view controllers associated with a
storyboard must be initialized from the client through a factory method on
the storyboard instance (storyboard. instantiateViewControllerWithIdentifier()).
This works when the entire flow of the app is storyboard based, but when a
single storyboard is used to configure a one-off view controller, having to
initialize through the storyboard is essentially use of private
implementation details; it shouldn’t matter whether the VC was designed in
code or storyboards, ultimately a single initializer should “do the right
thing” (just as it does when using XIBs directly). A factory initializer
for a View Controller subclass could handle the loading of the storyboard
and returning the appropriate view controller.

Here are some comments from the previous thread that I believe are still
relevant:

On Dec 9, 2015, at 1:06 PM, Philippe Hausler <phausler@apple.com> wrote:

I can definitely attest that in implementing Foundation we could have much
more idiomatic swift and much more similar behavior to the way Foundation
on Darwin actually works if we had factory initializers.

On Dec 7, 2015, at 5:24 PM, Brent Royal-Gordon <brent@architechies.com> > wrote:

A `protocol init` in a protocol extension creates an initializer which is
*not* applied to types conforming to the protocol. Instead, it is actually
an initializer on the protocol itself. `self` is the protocol metatype, not
an instance of anything. The provided implementation should `return` an
instance conforming to (and implicitly casted to) the protocol. Just like
any other initializer, a `protocol init` can be failable or throwing.

Unlike other initializers, Swift usually won’t be able to tell at compile
time which concrete type will be returned by a protocol init(), reducing
opportunities to statically bind methods and perform other optimization
tricks. Frankly, though, that’s just the cost of doing business. If you
want to select a type dynamically, you’re going to lose the ability to
aggressively optimize calls to the resulting instance.

I’d love to hear everyone’s thoughts on this!

Best,

Riley Testut

_______________________________________________

swift-evolution mailing list

swift-evolution@swift.org

https://lists.swift.org/mailman/listinfo/swift-evolution

_______________________________________________

swift-evolution mailing list

swift-evolution@swift.org

https://lists.swift.org/mailman/listinfo/swift-evolution

_______________________________________________
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution

_______________________________________________
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution

--
*Pranshu Goyal*
*iOS Developer*
*tlkn*

One concept to consider here is that the initializers that are factories may or may not replace self;

Take for example NSArray (inspired from the objective-c implementation but written in swift, but note this is not the only use case)

public init(objects: UnsafePointer<AnyObject>!, count cnt: Int) {
    if count == 0 && type(of: self) == NSArray.self {
        // specialized NSArray that does not contain any objects; it is a singleton so we dont need to allocate at all
        return __NSArray0.zeroElementSingleton
    } else if count == 1 type(of: self) == NSArray.self {
        // The single object version is more effecient since it does not need to indirect to a buffer
        return __NSArray1(objects.pointee)
    } else if type(of: self) == NSArray.self {
        return CFArrayCreate(kCFAllocatorSystemDefault, UnsafeMutablePointer<UnsafeRawPointer?>(objects), cnt, &kCFTypeArrayCallBacks)
    } else {
        _storage.reserveCapacity(cnt)
        for idx in 0..<cnt {
            _storage.append(objects[idx])
        }
    }
}

This would mean that in the cases of 0 elements when NSArray itself is created we can avoid allocating, when the count is 1 and it is an NSArray itself we can emit a more effecient storage, then when the type is immuatable we can fall to CF, and finally in the abstract case we can store elements in a buffer directly.

···

On Mar 21, 2017, at 4:28 PM, Charlie Monroe via swift-evolution <swift-evolution@swift.org> wrote:

I believe that this proposal is trying to solve something that can be solved by allowing assignment to self within convenience initializers.

Unfortunately, even convenience initializers are allocating which makes it harder to achieve with backward compatibility - though I'm not entirely sure what would be the consequences of turning them into non-allocating.

If it's not possible due to implementational details, I'd suggest to rather introduce a @nonallocating (or similar) annotation (keyword?) that can be placed on init methods and it would then require for self to be assigned during the initialization as long as the assigned value is subtype of the receiver:

@nonallocating init(x: Int) {
  if x < 0 {
    self = NegativeMe(x: x)
  } else {
    self = PositiveMe(x: x)
  }
}

Which is pretty much what the proposal is suggesting, but removes the "factory" keyword which may be a bit misleading or narrowly named.

On Mar 21, 2017, at 4:49 PM, David Rönnqvist via swift-evolution <swift-evolution@swift.org <mailto:swift-evolution@swift.org>> wrote:

Forgive me if that has already been discussed in the email threads prior to the proposal, but what I’m missing from this proposal is a discussion of the problems factory initializers solve (other than the examples at the end) and an explanation of why factory initializers are the right solution to that/those problems in Swift.

I acknowledge that it’s a common pattern in many languages, but don’t find it a very strong argument as to why it should be built into the language.

Regards,
David

On 17 Mar 2017, at 17:26, Riley Testut via swift-evolution <swift-evolution@swift.org <mailto:swift-evolution@swift.org>> wrote:

Hi again everyone!

Now that Swift 4 Stage 2 proposals are being considered, I thought it might be time to revisit this proposal and see if it might align with the goals set forth for Swift 4.

As a quick tl;dr, this proposal describes a new "factory initializer" that would allow you to return a value from an initializer. This would have several benefits, as mentioned in the proposal itself as well as throughout this mailing list. For convenience, here's a link to the proposal on GitHub: https://github.com/rileytestut/swift-evolution/blob/master/proposals/NNNN-factory-initializers.md

Would love to hear any more comments on this proposal, and if we feel this is appropriate for considering for Swift 4 I'll happily re-open the pull request!

Riley Testut

On Nov 19, 2016, at 7:45 AM, arkadi daniyelian <arkdan@icloud.com <mailto:arkdan@icloud.com>> wrote:

i would appreciate this feature.

For unexperienced developers, its often hard to recognize *when* factory is a good fit to do the job, and how exactly approach the implementation. I imagine having this feature built into the language may help to choose and implement factory when its the right thing to do.

On Nov 18, 2016, at 12:23 AM, Charles Srstka via swift-evolution <swift-evolution@swift.org <mailto:swift-evolution@swift.org>> wrote:

Is there any chance of reviving this? It seems to me that since this would require Swift initializers to be implemented internally in such a way that they can return a value (as Objective-C init methods do), it may affect ABI stability and thus may be germane to the current stage of Swift 4 development.

Charles

On Dec 17, 2015, at 3:41 PM, Riley Testut via swift-evolution <swift-evolution@swift.org <mailto:swift-evolution@swift.org>> wrote:

Recently, I proposed the idea of adding the ability to implement the "class cluster" pattern from Cocoa (Touch) in Swift. However, as we discussed it and came up with different approaches, it evolved into a functionality that I believe is far more beneficial to Swift, and subsequently should be the focus of its own proposal. So here is the improved (pre-)proposal:

# Factory Initializers

The "factory" pattern is common in many languages, including Objective-C. Essentially, instead of initializing a type directly, a method is called that returns an instance of the appropriate type determined by the input parameters. Functionally this works well, but ultimately it forces the client of the API to remember to call the factory method instead, rather than the type's initializer. This might seem like a minor gripe, but given that we want Swift to be as approachable as possible to new developers, I think we can do better in this regard.

Rather than have a separate factory method, I propose we build the factory pattern right into Swift, by way of specialized “factory initializers”. The exact syntax was proposed by Philippe Hausler from the previous thread, and I think it is an excellent solution:

class AbstractBase {
public factory init(type: InformationToSwitchOn) {
     return ConcreteImplementation(type)
}
}

class ConcreteImplementation : AbstractBase {

}

Why exactly would this be useful in practice? In my own development, I’ve come across a few places where this would especially be relevant:

## Class Cluster/Abstract Classes
This was the reasoning behind the original proposal, and I still think it would be a very valid use case. The public superclass would declare all the public methods, and could delegate off the specific implementations to the private subclasses. Alternatively, this method could be used as an easy way to handle backwards-compatibility: rather than litter the code with branches depending on the OS version, simply return the OS-appropriate subclass from the factory initializer. Very useful.

## Protocol Initializers
Proposed by Brent Royal-Gordon, we could use factory initializers with protocol extensions to return the appropriate instance conforming to a protocol for the given needs. Similar to the class cluster/abstract class method, but can work with structs too. This would be closer to the factory method pattern, since you don’t need to know exactly what type is returned, just the protocol it conforms to.

## Initializing Storyboard-backed View Controller
This is more specific to Apple Frameworks, but having factory initializers could definitely help here. Currently, view controllers associated with a storyboard must be initialized from the client through a factory method on the storyboard instance (storyboard. instantiateViewControllerWithIdentifier()). This works when the entire flow of the app is storyboard based, but when a single storyboard is used to configure a one-off view controller, having to initialize through the storyboard is essentially use of private implementation details; it shouldn’t matter whether the VC was designed in code or storyboards, ultimately a single initializer should “do the right thing” (just as it does when using XIBs directly). A factory initializer for a View Controller subclass could handle the loading of the storyboard and returning the appropriate view controller.

Here are some comments from the previous thread that I believe are still relevant:

On Dec 9, 2015, at 1:06 PM, Philippe Hausler <phausler@apple.com <mailto:phausler@apple.com>> wrote:

I can definitely attest that in implementing Foundation we could have much more idiomatic swift and much more similar behavior to the way Foundation on Darwin actually works if we had factory initializers.

On Dec 7, 2015, at 5:24 PM, Brent Royal-Gordon <brent@architechies.com <mailto:brent@architechies.com>> wrote:

A `protocol init` in a protocol extension creates an initializer which is *not* applied to types conforming to the protocol. Instead, it is actually an initializer on the protocol itself. `self` is the protocol metatype, not an instance of anything. The provided implementation should `return` an instance conforming to (and implicitly casted to) the protocol. Just like any other initializer, a `protocol init` can be failable or throwing.

Unlike other initializers, Swift usually won’t be able to tell at compile time which concrete type will be returned by a protocol init(), reducing opportunities to statically bind methods and perform other optimization tricks. Frankly, though, that’s just the cost of doing business. If you want to select a type dynamically, you’re going to lose the ability to aggressively optimize calls to the resulting instance.

I’d love to hear everyone’s thoughts on this!

Best,
Riley Testut
_______________________________________________
swift-evolution mailing list
swift-evolution@swift.org <mailto:swift-evolution@swift.org>
https://lists.swift.org/mailman/listinfo/swift-evolution

_______________________________________________
swift-evolution mailing list
swift-evolution@swift.org <mailto:swift-evolution@swift.org>
https://lists.swift.org/mailman/listinfo/swift-evolution

_______________________________________________
swift-evolution mailing list
swift-evolution@swift.org <mailto:swift-evolution@swift.org>
https://lists.swift.org/mailman/listinfo/swift-evolution

_______________________________________________
swift-evolution mailing list
swift-evolution@swift.org <mailto:swift-evolution@swift.org>
https://lists.swift.org/mailman/listinfo/swift-evolution

_______________________________________________
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution

This was kind of my point - all current class initializers are allocating. Allowing non-allocating initializers would solve most cases, including factory methods.

The last else statement in your example (for a regular case) can definitely return a value from another initializer - e.g. init(reservingCapacity:).

I wouldn't go for the return statement, but rather assignment to self - this is more in line with to how the convenience initializers work - you can branch based on the input and call designated initializers accordingly.

The same way, you could assign to self and then access instance variables within self.

Taking your example, all returns would be assignment to self and the last branch of the if-else statement would read as follows:

self = self.init(reservingCapacity: cnt)
for idx in 0..<cnt {
    // It's OK now to access _storage as we've previously
    // assigned to self.
     _storage.append(objects[idx])
}

···

On Mar 21, 2017, at 6:04 PM, Philippe Hausler <phausler@apple.com> wrote:

One concept to consider here is that the initializers that are factories may or may not replace self;

Take for example NSArray (inspired from the objective-c implementation but written in swift, but note this is not the only use case)

public init(objects: UnsafePointer<AnyObject>!, count cnt: Int) {
    if count == 0 && type(of: self) == NSArray.self {
        // specialized NSArray that does not contain any objects; it is a singleton so we dont need to allocate at all
        return __NSArray0.zeroElementSingleton
    } else if count == 1 type(of: self) == NSArray.self {
        // The single object version is more effecient since it does not need to indirect to a buffer
        return __NSArray1(objects.pointee)
    } else if type(of: self) == NSArray.self {
        return CFArrayCreate(kCFAllocatorSystemDefault, UnsafeMutablePointer<UnsafeRawPointer?>(objects), cnt, &kCFTypeArrayCallBacks)
    } else {
        _storage.reserveCapacity(cnt)
        for idx in 0..<cnt {
            _storage.append(objects[idx])
        }
    }
}

This would mean that in the cases of 0 elements when NSArray itself is created we can avoid allocating, when the count is 1 and it is an NSArray itself we can emit a more effecient storage, then when the type is immuatable we can fall to CF, and finally in the abstract case we can store elements in a buffer directly.

On Mar 21, 2017, at 4:28 PM, Charlie Monroe via swift-evolution <swift-evolution@swift.org <mailto:swift-evolution@swift.org>> wrote:

I believe that this proposal is trying to solve something that can be solved by allowing assignment to self within convenience initializers.

Unfortunately, even convenience initializers are allocating which makes it harder to achieve with backward compatibility - though I'm not entirely sure what would be the consequences of turning them into non-allocating.

If it's not possible due to implementational details, I'd suggest to rather introduce a @nonallocating (or similar) annotation (keyword?) that can be placed on init methods and it would then require for self to be assigned during the initialization as long as the assigned value is subtype of the receiver:

@nonallocating init(x: Int) {
  if x < 0 {
    self = NegativeMe(x: x)
  } else {
    self = PositiveMe(x: x)
  }
}

Which is pretty much what the proposal is suggesting, but removes the "factory" keyword which may be a bit misleading or narrowly named.

On Mar 21, 2017, at 4:49 PM, David Rönnqvist via swift-evolution <swift-evolution@swift.org <mailto:swift-evolution@swift.org>> wrote:

Forgive me if that has already been discussed in the email threads prior to the proposal, but what I’m missing from this proposal is a discussion of the problems factory initializers solve (other than the examples at the end) and an explanation of why factory initializers are the right solution to that/those problems in Swift.

I acknowledge that it’s a common pattern in many languages, but don’t find it a very strong argument as to why it should be built into the language.

Regards,
David

On 17 Mar 2017, at 17:26, Riley Testut via swift-evolution <swift-evolution@swift.org <mailto:swift-evolution@swift.org>> wrote:

Hi again everyone!

Now that Swift 4 Stage 2 proposals are being considered, I thought it might be time to revisit this proposal and see if it might align with the goals set forth for Swift 4.

As a quick tl;dr, this proposal describes a new "factory initializer" that would allow you to return a value from an initializer. This would have several benefits, as mentioned in the proposal itself as well as throughout this mailing list. For convenience, here's a link to the proposal on GitHub: https://github.com/rileytestut/swift-evolution/blob/master/proposals/NNNN-factory-initializers.md

Would love to hear any more comments on this proposal, and if we feel this is appropriate for considering for Swift 4 I'll happily re-open the pull request!

Riley Testut

On Nov 19, 2016, at 7:45 AM, arkadi daniyelian <arkdan@icloud.com <mailto:arkdan@icloud.com>> wrote:

i would appreciate this feature.

For unexperienced developers, its often hard to recognize *when* factory is a good fit to do the job, and how exactly approach the implementation. I imagine having this feature built into the language may help to choose and implement factory when its the right thing to do.

On Nov 18, 2016, at 12:23 AM, Charles Srstka via swift-evolution <swift-evolution@swift.org <mailto:swift-evolution@swift.org>> wrote:

Is there any chance of reviving this? It seems to me that since this would require Swift initializers to be implemented internally in such a way that they can return a value (as Objective-C init methods do), it may affect ABI stability and thus may be germane to the current stage of Swift 4 development.

Charles

On Dec 17, 2015, at 3:41 PM, Riley Testut via swift-evolution <swift-evolution@swift.org <mailto:swift-evolution@swift.org>> wrote:

Recently, I proposed the idea of adding the ability to implement the "class cluster" pattern from Cocoa (Touch) in Swift. However, as we discussed it and came up with different approaches, it evolved into a functionality that I believe is far more beneficial to Swift, and subsequently should be the focus of its own proposal. So here is the improved (pre-)proposal:

# Factory Initializers

The "factory" pattern is common in many languages, including Objective-C. Essentially, instead of initializing a type directly, a method is called that returns an instance of the appropriate type determined by the input parameters. Functionally this works well, but ultimately it forces the client of the API to remember to call the factory method instead, rather than the type's initializer. This might seem like a minor gripe, but given that we want Swift to be as approachable as possible to new developers, I think we can do better in this regard.

Rather than have a separate factory method, I propose we build the factory pattern right into Swift, by way of specialized “factory initializers”. The exact syntax was proposed by Philippe Hausler from the previous thread, and I think it is an excellent solution:

class AbstractBase {
public factory init(type: InformationToSwitchOn) {
     return ConcreteImplementation(type)
}
}

class ConcreteImplementation : AbstractBase {

}

Why exactly would this be useful in practice? In my own development, I’ve come across a few places where this would especially be relevant:

## Class Cluster/Abstract Classes
This was the reasoning behind the original proposal, and I still think it would be a very valid use case. The public superclass would declare all the public methods, and could delegate off the specific implementations to the private subclasses. Alternatively, this method could be used as an easy way to handle backwards-compatibility: rather than litter the code with branches depending on the OS version, simply return the OS-appropriate subclass from the factory initializer. Very useful.

## Protocol Initializers
Proposed by Brent Royal-Gordon, we could use factory initializers with protocol extensions to return the appropriate instance conforming to a protocol for the given needs. Similar to the class cluster/abstract class method, but can work with structs too. This would be closer to the factory method pattern, since you don’t need to know exactly what type is returned, just the protocol it conforms to.

## Initializing Storyboard-backed View Controller
This is more specific to Apple Frameworks, but having factory initializers could definitely help here. Currently, view controllers associated with a storyboard must be initialized from the client through a factory method on the storyboard instance (storyboard. instantiateViewControllerWithIdentifier()). This works when the entire flow of the app is storyboard based, but when a single storyboard is used to configure a one-off view controller, having to initialize through the storyboard is essentially use of private implementation details; it shouldn’t matter whether the VC was designed in code or storyboards, ultimately a single initializer should “do the right thing” (just as it does when using XIBs directly). A factory initializer for a View Controller subclass could handle the loading of the storyboard and returning the appropriate view controller.

Here are some comments from the previous thread that I believe are still relevant:

On Dec 9, 2015, at 1:06 PM, Philippe Hausler <phausler@apple.com <mailto:phausler@apple.com>> wrote:

I can definitely attest that in implementing Foundation we could have much more idiomatic swift and much more similar behavior to the way Foundation on Darwin actually works if we had factory initializers.

On Dec 7, 2015, at 5:24 PM, Brent Royal-Gordon <brent@architechies.com <mailto:brent@architechies.com>> wrote:

A `protocol init` in a protocol extension creates an initializer which is *not* applied to types conforming to the protocol. Instead, it is actually an initializer on the protocol itself. `self` is the protocol metatype, not an instance of anything. The provided implementation should `return` an instance conforming to (and implicitly casted to) the protocol. Just like any other initializer, a `protocol init` can be failable or throwing.

Unlike other initializers, Swift usually won’t be able to tell at compile time which concrete type will be returned by a protocol init(), reducing opportunities to statically bind methods and perform other optimization tricks. Frankly, though, that’s just the cost of doing business. If you want to select a type dynamically, you’re going to lose the ability to aggressively optimize calls to the resulting instance.

I’d love to hear everyone’s thoughts on this!

Best,
Riley Testut
_______________________________________________
swift-evolution mailing list
swift-evolution@swift.org <mailto:swift-evolution@swift.org>
https://lists.swift.org/mailman/listinfo/swift-evolution

_______________________________________________
swift-evolution mailing list
swift-evolution@swift.org <mailto:swift-evolution@swift.org>
https://lists.swift.org/mailman/listinfo/swift-evolution

_______________________________________________
swift-evolution mailing list
swift-evolution@swift.org <mailto:swift-evolution@swift.org>
https://lists.swift.org/mailman/listinfo/swift-evolution

_______________________________________________
swift-evolution mailing list
swift-evolution@swift.org <mailto:swift-evolution@swift.org>
https://lists.swift.org/mailman/listinfo/swift-evolution

_______________________________________________
swift-evolution mailing list
swift-evolution@swift.org <mailto:swift-evolution@swift.org>
https://lists.swift.org/mailman/listinfo/swift-evolution

This needs more explanation. It is allowed for a subclass to implement a convenience initializer that has the same signature as a superclass convenience initializer or a superclass designated initializer. The convenience-over-convenience case is not technically overriding, but it is misleading to say only that a convenience initializer cannot be overridden. Do factory initializers follow exactly the same rules here as convenience initializers?

Yes, that is what I meant. For simplicity, I think the factory initializer inheritance rules should match exactly that of convenience initializers.

In addition: designated initializers and convenience initializers have rules about which other initializers can be called from an implementation. These rules are intended to guarantee that the chain of designated initializers is called correctly. What are the precise rules for factory initializers calling other initializers? What are the precise rules for non-factory initializers calling factory initializers?

Factory initializers can call any other initializers. Since calling convenience initializers would still call required initializers, the chain would be correct (unless I’m missing something). As for other initializers calling factory initializers, my gut says this should not be allowed. Factory initializers are supposed to initialize and return a value, whereas other initializers implicitly assign to self. Therefore calling a factory initializer from a self-assigning initializer wouldn’t do much, and I don’t see any benefit to allowing this.

···

On Mar 20, 2017, at 8:07 PM, Greg Parker <gparker@apple.com> wrote:

On Mar 21, 2017, at 8:49 AM, David Rönnqvist <david.ronnqvist@gmail.com> wrote:

Forgive me if that has already been discussed in the email threads prior to the proposal, but what I’m missing from this proposal is a discussion of the problems factory initializers solve (other than the examples at the end) and an explanation of why factory initializers are the right solution to that/those problems in Swift.

I can answer this anecdotally; when learning iOS development and Objective-C, it was (in my opinion) hard to know whether an Objective-C class was meant to be initialized via [[Class alloc] initWithParameters:] or [Class classWithParameters:]. Pre-ARC this did actually have meaning, but post ARC/iOS 5 it just seemed to be whatever the framework developer preferred (not to mention that [Class new] was also another option…).

When Swift combined all these forms into one common Class(parameters:) format, this greatly reduced this cognitive load. However, as outlined in the proposal, this meant that the factory pattern had to be moved out of the initializers and back into class methods. Because of this, now if you want to implement the factory pattern, you’re bringing back this same confusion from Objective-C; the client has to remember whether your class is initialized via standard Class(parameters:) syntax, or by calling a class method Class.classWithParameters(). Ultimately, I don’t believe there should be a difference between the two for the average programmer. You want an instance of the class, so you should retrieve one by calling an initializer. They don’t need to know or care whether the initializer is directly assigning to self or returning a value, as long as they get the value they need.

Beyond this, however, I think the factory initializers on protocols is one of this proposal’s biggest wins. For protocol oriented programming, it’s nice to be apply to supply a default implementation so client’s don’t need to declare their own type. However, if you come across a new codebase/framework, you might not know the difference between the specific type you’re using and the protocol itself (or even which one is which). I’ve personally encountered this many times with Apple’s frameworks, such as UIActivityItemProvider and UIActivityItemSource (which one is the protocol and which one is the type? Hard to know and remember when first using them). With factory initializers on protocol extensions, the initializer can return a private type conforming to the protocol, so again there’s no need to worry about what is the concrete type and what is the protocol.

P.S. Phase 2 End Question

I didn’t realize until today that apparently Swift 4 Phase 2 ends tomorrow. Is this true, and does that mean this is now too late to make it into Swift 4?

No.

···

On Sun, Jun 4, 2017 at 10:07 Pranshu Goyal via swift-evolution < swift-evolution@swift.org> wrote:

Is this proposal in the pipeline for Swift 4?

On 1 April 2017 at 12:03, Adrian Zubarev via swift-evolution < > swift-evolution@swift.org> wrote:

First, you should fix the indent in the code samples. Second, remove any
access modifier from inside a protocol. Third, we don’t support default
implementations directly inside protocols yet, so that’s a not valid
example.

Now my personal concerns. As far as I can tell XIB files in an iOS
Project are meant for UIViewControllers in first place, but it’s a common
case that they are also used to create reusable UIViews. The downside of
that abusage is view hierarchy clustering. Most developer creating a view
of Self in Self, which smells to me like really bad code.

MyCustomView // This view is useless
   + MyCustomView
       + CustomSubview1
   + CustomSubview1 // This is probably a dead IBOutlet

In fact Xcode does not use the initializer from NSCoding to show a live
rendered view inside interface builder, instead it will call a UIViews
designated initializer init(frame:). That results that a lot of the
developer write similar code like in the following snippet:

// This pattern results in a similar view cluster like mentioned above

class MyCustomView : UIView {
    override init(frame: CGRect) {
        let view = loadSomehowFromNib()
        self.addSubview(view)
    }
}

To solve this problem we’d need some functionality of factory
initializers. I believe as proposed the factory initializer won’t solve
that problem, because everything would be still restricted to a special
initializer annotated with factory.

Personally I would want to write something like this instead.

class MyCustomView : UIView {

    override init(frame: CGRect) {

        // Instantiating from a Nib file will call `init(coder:​)` on MyCustomView
        self = loadSomehowFromNib() // assuming () -> MyCustomView

        //
        self.frame = frame
    }
}

This should resolve the clustering issue by assigning the returned
instance from the function to self and create a correct view hierarchy.

+ MyCustomView
       + CustomSubview1

--
Adrian Zubarev
Sent with Airmail

Am 17. März 2017 um 17:26:29, Riley Testut via swift-evolution (
swift-evolution@swift.org) schrieb:

Hi again everyone!

Now that Swift 4 Stage 2 proposals are being considered, I thought it
might be time to revisit this proposal and see if it might align with the
goals set forth for Swift 4.

As a quick tl;dr, this proposal describes a new "factory initializer"
that would allow you to return a value from an initializer. This would have
several benefits, as mentioned in the proposal itself as well as throughout
this mailing list. For convenience, here's a link to the proposal on
GitHub:
https://github.com/rileytestut/swift-evolution/blob/master/proposals/NNNN-factory-initializers.md

Would love to hear any more comments on this proposal, and if we feel
this is appropriate for considering for Swift 4 I'll happily re-open the
pull request!

Riley Testut

On Nov 19, 2016, at 7:45 AM, arkadi daniyelian <arkdan@icloud.com> wrote:

i would appreciate this feature.

For unexperienced developers, its often hard to recognize *when* factory
is a good fit to do the job, and how exactly approach the implementation. I
imagine having this feature built into the language may help to choose and
implement factory when its the right thing to do.

On Nov 18, 2016, at 12:23 AM, Charles Srstka via swift-evolution < >> swift-evolution@swift.org> wrote:

Is there any chance of reviving this? It seems to me that since this
would require Swift initializers to be implemented internally in such a way
that they can return a value (as Objective-C init methods do), it may
affect ABI stability and thus may be germane to the current stage of Swift
4 development.

Charles

On Dec 17, 2015, at 3:41 PM, Riley Testut via swift-evolution < >> swift-evolution@swift.org> wrote:

Recently, I proposed the idea of adding the ability to implement the
"class cluster" pattern from Cocoa (Touch) in Swift. However, as we
discussed it and came up with different approaches, it evolved into a
functionality that I believe is far more beneficial to Swift, and
subsequently should be the focus of its own proposal. So here is the
improved (pre-)proposal:

# Factory Initializers

The "factory" pattern is common in many languages, including Objective-C.
Essentially, instead of initializing a type directly, a method is called
that returns an instance of the appropriate type determined by the input
parameters. Functionally this works well, but ultimately it forces the
client of the API to remember to call the factory method instead, rather
than the type's initializer. This might seem like a minor gripe, but given
that we want Swift to be as approachable as possible to new developers, I
think we can do better in this regard.

Rather than have a separate factory method, I propose we build the
factory pattern right into Swift, by way of specialized “factory
initializers”. The exact syntax was proposed by Philippe Hausler from the
previous thread, and I think it is an excellent solution:

class AbstractBase {

public factory init(type: InformationToSwitchOn) {

     return ConcreteImplementation(type)

}

}

class ConcreteImplementation : AbstractBase {

}

Why exactly would this be useful in practice? In my own development, I’ve
come across a few places where this would especially be relevant:

## Class Cluster/Abstract Classes

This was the reasoning behind the original proposal, and I still think it
would be a very valid use case. The public superclass would declare all the
public methods, and could delegate off the specific implementations to the
private subclasses. Alternatively, this method could be used as an easy way
to handle backwards-compatibility: rather than litter the code with
branches depending on the OS version, simply return the OS-appropriate
subclass from the factory initializer. Very useful.

## Protocol Initializers

Proposed by Brent Royal-Gordon, we could use factory initializers with
protocol extensions to return the appropriate instance conforming to a
protocol for the given needs. Similar to the class cluster/abstract class
method, but can work with structs too. This would be closer to the factory
method pattern, since you don’t need to know exactly what type is returned,
just the protocol it conforms to.

## Initializing Storyboard-backed View Controller

This is more specific to Apple Frameworks, but having factory
initializers could definitely help here. Currently, view controllers
associated with a storyboard must be initialized from the client through a
factory method on the storyboard instance (storyboard.
instantiateViewControllerWithIdentifier()). This works when the entire flow
of the app is storyboard based, but when a single storyboard is used to
configure a one-off view controller, having to initialize through the
storyboard is essentially use of private implementation details; it
shouldn’t matter whether the VC was designed in code or storyboards,
ultimately a single initializer should “do the right thing” (just as it
does when using XIBs directly). A factory initializer for a View Controller
subclass could handle the loading of the storyboard and returning the
appropriate view controller.

Here are some comments from the previous thread that I believe are still
relevant:

On Dec 9, 2015, at 1:06 PM, Philippe Hausler <phausler@apple.com> wrote:

I can definitely attest that in implementing Foundation we could have
much more idiomatic swift and much more similar behavior to the way
Foundation on Darwin actually works if we had factory initializers.

On Dec 7, 2015, at 5:24 PM, Brent Royal-Gordon <brent@architechies.com> >> wrote:

A `protocol init` in a protocol extension creates an initializer which is
*not* applied to types conforming to the protocol. Instead, it is actually
an initializer on the protocol itself. `self` is the protocol metatype, not
an instance of anything. The provided implementation should `return` an
instance conforming to (and implicitly casted to) the protocol. Just like
any other initializer, a `protocol init` can be failable or throwing.

Unlike other initializers, Swift usually won’t be able to tell at compile
time which concrete type will be returned by a protocol init(), reducing
opportunities to statically bind methods and perform other optimization
tricks. Frankly, though, that’s just the cost of doing business. If you
want to select a type dynamically, you’re going to lose the ability to
aggressively optimize calls to the resulting instance.

I’d love to hear everyone’s thoughts on this!

Best,

Riley Testut

_______________________________________________

swift-evolution mailing list

swift-evolution@swift.org

https://lists.swift.org/mailman/listinfo/swift-evolution

_______________________________________________

swift-evolution mailing list

swift-evolution@swift.org

https://lists.swift.org/mailman/listinfo/swift-evolution

_______________________________________________
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution

_______________________________________________
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution

--
*Pranshu Goyal*
*iOS Developer*
*tlkn*
_______________________________________________
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution

Any hopes for it in future?

···

On 4 June 2017 at 20:40, Xiaodi Wu <xiaodi.wu@gmail.com> wrote:

No.

On Sun, Jun 4, 2017 at 10:07 Pranshu Goyal via swift-evolution < > swift-evolution@swift.org> wrote:

Is this proposal in the pipeline for Swift 4?

On 1 April 2017 at 12:03, Adrian Zubarev via swift-evolution < >> swift-evolution@swift.org> wrote:

First, you should fix the indent in the code samples. Second, remove any
access modifier from inside a protocol. Third, we don’t support default
implementations directly inside protocols yet, so that’s a not valid
example.

Now my personal concerns. As far as I can tell XIB files in an iOS
Project are meant for UIViewControllers in first place, but it’s a common
case that they are also used to create reusable UIViews. The downside of
that abusage is view hierarchy clustering. Most developer creating a view
of Self in Self, which smells to me like really bad code.

MyCustomView // This view is useless
   + MyCustomView
       + CustomSubview1
   + CustomSubview1 // This is probably a dead IBOutlet

In fact Xcode does not use the initializer from NSCoding to show a live
rendered view inside interface builder, instead it will call a UIViews
designated initializer init(frame:). That results that a lot of the
developer write similar code like in the following snippet:

// This pattern results in a similar view cluster like mentioned above

class MyCustomView : UIView {
    override init(frame: CGRect) {
        let view = loadSomehowFromNib()
        self.addSubview(view)
    }
}

To solve this problem we’d need some functionality of factory
initializers. I believe as proposed the factory initializer won’t solve
that problem, because everything would be still restricted to a special
initializer annotated with factory.

Personally I would want to write something like this instead.

class MyCustomView : UIView {

    override init(frame: CGRect) {

        // Instantiating from a Nib file will call `init(coder:​)` on MyCustomView
        self = loadSomehowFromNib() // assuming () -> MyCustomView

        //
        self.frame = frame
    }
}

This should resolve the clustering issue by assigning the returned
instance from the function to self and create a correct view hierarchy.

+ MyCustomView
       + CustomSubview1

--
Adrian Zubarev
Sent with Airmail

Am 17. März 2017 um 17:26:29, Riley Testut via swift-evolution (
swift-evolution@swift.org) schrieb:

Hi again everyone!

Now that Swift 4 Stage 2 proposals are being considered, I thought it
might be time to revisit this proposal and see if it might align with the
goals set forth for Swift 4.

As a quick tl;dr, this proposal describes a new "factory initializer"
that would allow you to return a value from an initializer. This would have
several benefits, as mentioned in the proposal itself as well as throughout
this mailing list. For convenience, here's a link to the proposal on
GitHub: GitHub - rileytestut/swift-evolution: This maintains proposals for changes and user-visible enhancements to the Swift Programming Language.
blob/master/proposals/NNNN-factory-initializers.md

Would love to hear any more comments on this proposal, and if we feel
this is appropriate for considering for Swift 4 I'll happily re-open the
pull request!

Riley Testut

On Nov 19, 2016, at 7:45 AM, arkadi daniyelian <arkdan@icloud.com> >>> wrote:

i would appreciate this feature.

For unexperienced developers, its often hard to recognize *when* factory
is a good fit to do the job, and how exactly approach the implementation. I
imagine having this feature built into the language may help to choose and
implement factory when its the right thing to do.

On Nov 18, 2016, at 12:23 AM, Charles Srstka via swift-evolution < >>> swift-evolution@swift.org> wrote:

Is there any chance of reviving this? It seems to me that since this
would require Swift initializers to be implemented internally in such a way
that they can return a value (as Objective-C init methods do), it may
affect ABI stability and thus may be germane to the current stage of Swift
4 development.

Charles

On Dec 17, 2015, at 3:41 PM, Riley Testut via swift-evolution < >>> swift-evolution@swift.org> wrote:

Recently, I proposed the idea of adding the ability to implement the
"class cluster" pattern from Cocoa (Touch) in Swift. However, as we
discussed it and came up with different approaches, it evolved into a
functionality that I believe is far more beneficial to Swift, and
subsequently should be the focus of its own proposal. So here is the
improved (pre-)proposal:

# Factory Initializers

The "factory" pattern is common in many languages, including
Objective-C. Essentially, instead of initializing a type directly, a method
is called that returns an instance of the appropriate type determined by
the input parameters. Functionally this works well, but ultimately it
forces the client of the API to remember to call the factory method
instead, rather than the type's initializer. This might seem like a minor
gripe, but given that we want Swift to be as approachable as possible to
new developers, I think we can do better in this regard.

Rather than have a separate factory method, I propose we build the
factory pattern right into Swift, by way of specialized “factory
initializers”. The exact syntax was proposed by Philippe Hausler from the
previous thread, and I think it is an excellent solution:

class AbstractBase {

public factory init(type: InformationToSwitchOn) {

     return ConcreteImplementation(type)

}

}

class ConcreteImplementation : AbstractBase {

}

Why exactly would this be useful in practice? In my own development,
I’ve come across a few places where this would especially be relevant:

## Class Cluster/Abstract Classes

This was the reasoning behind the original proposal, and I still think
it would be a very valid use case. The public superclass would declare all
the public methods, and could delegate off the specific implementations to
the private subclasses. Alternatively, this method could be used as an easy
way to handle backwards-compatibility: rather than litter the code with
branches depending on the OS version, simply return the OS-appropriate
subclass from the factory initializer. Very useful.

## Protocol Initializers

Proposed by Brent Royal-Gordon, we could use factory initializers with
protocol extensions to return the appropriate instance conforming to a
protocol for the given needs. Similar to the class cluster/abstract class
method, but can work with structs too. This would be closer to the factory
method pattern, since you don’t need to know exactly what type is returned,
just the protocol it conforms to.

## Initializing Storyboard-backed View Controller

This is more specific to Apple Frameworks, but having factory
initializers could definitely help here. Currently, view controllers
associated with a storyboard must be initialized from the client through a
factory method on the storyboard instance (storyboard.
instantiateViewControllerWithIdentifier()). This works when the entire
flow of the app is storyboard based, but when a single storyboard is used
to configure a one-off view controller, having to initialize through the
storyboard is essentially use of private implementation details; it
shouldn’t matter whether the VC was designed in code or storyboards,
ultimately a single initializer should “do the right thing” (just as it
does when using XIBs directly). A factory initializer for a View Controller
subclass could handle the loading of the storyboard and returning the
appropriate view controller.

Here are some comments from the previous thread that I believe are still
relevant:

On Dec 9, 2015, at 1:06 PM, Philippe Hausler <phausler@apple.com> wrote:

I can definitely attest that in implementing Foundation we could have
much more idiomatic swift and much more similar behavior to the way
Foundation on Darwin actually works if we had factory initializers.

On Dec 7, 2015, at 5:24 PM, Brent Royal-Gordon <brent@architechies.com> >>> wrote:

A `protocol init` in a protocol extension creates an initializer which
is *not* applied to types conforming to the protocol. Instead, it is
actually an initializer on the protocol itself. `self` is the protocol
metatype, not an instance of anything. The provided implementation should
`return` an instance conforming to (and implicitly casted to) the protocol.
Just like any other initializer, a `protocol init` can be failable or
throwing.

Unlike other initializers, Swift usually won’t be able to tell at
compile time which concrete type will be returned by a protocol init(),
reducing opportunities to statically bind methods and perform other
optimization tricks. Frankly, though, that’s just the cost of doing
business. If you want to select a type dynamically, you’re going to lose
the ability to aggressively optimize calls to the resulting instance.

I’d love to hear everyone’s thoughts on this!

Best,

Riley Testut

_______________________________________________

swift-evolution mailing list

swift-evolution@swift.org

https://lists.swift.org/mailman/listinfo/swift-evolution

_______________________________________________

swift-evolution mailing list

swift-evolution@swift.org

https://lists.swift.org/mailman/listinfo/swift-evolution

_______________________________________________
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution

_______________________________________________
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution

--
*Pranshu Goyal*
*iOS Developer*
*tlkn*
_______________________________________________
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution

--
*Pranshu Goyal*
*iOS Developer*
*tlkn*

This needs more explanation. It is allowed for a subclass to implement a convenience initializer that has the same signature as a superclass convenience initializer or a superclass designated initializer. The convenience-over-convenience case is not technically overriding, but it is misleading to say only that a convenience initializer cannot be overridden. Do factory initializers follow exactly the same rules here as convenience initializers?

Yes, that is what I meant. For simplicity, I think the factory initializer inheritance rules should match exactly that of convenience initializers.

In addition: designated initializers and convenience initializers have rules about which other initializers can be called from an implementation. These rules are intended to guarantee that the chain of designated initializers is called correctly. What are the precise rules for factory initializers calling other initializers? What are the precise rules for non-factory initializers calling factory initializers?

Factory initializers can call any other initializers. Since calling convenience initializers would still call required initializers, the chain would be correct (unless I’m missing something). As for other initializers calling factory initializers, my gut says this should not be allowed. Factory initializers are supposed to initialize and return a value, whereas other initializers implicitly assign to self. Therefore calling a factory initializer from a self-assigning initializer wouldn’t do much, and I don’t see any benefit to allowing this.

Forgive me if that has already been discussed in the email threads prior to the proposal, but what I’m missing from this proposal is a discussion of the problems factory initializers solve (other than the examples at the end) and an explanation of why factory initializers are the right solution to that/those problems in Swift.

I can answer this anecdotally; when learning iOS development and Objective-C, it was (in my opinion) hard to know whether an Objective-C class was meant to be initialized via [[Class alloc] initWithParameters:] or [Class classWithParameters:]. Pre-ARC this did actually have meaning, but post ARC/iOS 5 it just seemed to be whatever the framework developer preferred (not to mention that [Class new] was also another option…).

When Swift combined all these forms into one common Class(parameters:) format, this greatly reduced this cognitive load. However, as outlined in the proposal, this meant that the factory pattern had to be moved out of the initializers and back into class methods. Because of this, now if you want to implement the factory pattern, you’re bringing back this same confusion from Objective-C; the client has to remember whether your class is initialized via standard Class(parameters:) syntax, or by calling a class method Class.classWithParameters(). Ultimately, I don’t believe there should be a difference between the two for the average programmer. You want an instance of the class, so you should retrieve one by calling an initializer. They don’t need to know or care whether the initializer is directly assigning to self or returning a value, as long as they get the value they need.

Beyond this, however, I think the factory initializers on protocols is one of this proposal’s biggest wins. For protocol oriented programming, it’s nice to be apply to supply a default implementation so client’s don’t need to declare their own type. However, if you come across a new codebase/framework, you might not know the difference between the specific type you’re using and the protocol itself (or even which one is which). I’ve personally encountered this many times with Apple’s frameworks, such as UIActivityItemProvider and UIActivityItemSource (which one is the protocol and which one is the type? Hard to know and remember when first using them). With factory initializers on protocol extensions, the initializer can return a private type conforming to the protocol, so again there’s no need to worry about what is the concrete type and what is the protocol.

P.S. Phase 2 End Question

I didn’t realize until today that apparently Swift 4 Phase 2 ends tomorrow. Is this true, and does that mean this is now too late to make it into Swift 4?

Did not realise it either... does this mean that we are not getting argument labels in closures passed to functions back as it was promised last year? :(

···

Sent from my iPhone

On 1 Apr 2017, at 00:35, Riley Testut via swift-evolution <swift-evolution@swift.org> wrote:

On Mar 20, 2017, at 8:07 PM, Greg Parker <gparker@apple.com> wrote:
On Mar 21, 2017, at 8:49 AM, David Rönnqvist <david.ronnqvist@gmail.com> wrote:

_______________________________________________
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution

This needs more explanation. It is allowed for a subclass to implement a convenience initializer that has the same signature as a superclass convenience initializer or a superclass designated initializer. The convenience-over-convenience case is not technically overriding, but it is misleading to say only that a convenience initializer cannot be overridden. Do factory initializers follow exactly the same rules here as convenience initializers?

Yes, that is what I meant. For simplicity, I think the factory initializer inheritance rules should match exactly that of convenience initializers.

In addition: designated initializers and convenience initializers have rules about which other initializers can be called from an implementation. These rules are intended to guarantee that the chain of designated initializers is called correctly. What are the precise rules for factory initializers calling other initializers? What are the precise rules for non-factory initializers calling factory initializers?

Factory initializers can call any other initializers. Since calling convenience initializers would still call required initializers, the chain would be correct (unless I’m missing something). As for other initializers calling factory initializers, my gut says this should not be allowed. Factory initializers are supposed to initialize and return a value, whereas other initializers implicitly assign to self. Therefore calling a factory initializer from a self-assigning initializer wouldn’t do much, and I don’t see any benefit to allowing this.

Forgive me if that has already been discussed in the email threads prior to the proposal, but what I’m missing from this proposal is a discussion of the problems factory initializers solve (other than the examples at the end) and an explanation of why factory initializers are the right solution to that/those problems in Swift.

I can answer this anecdotally; when learning iOS development and Objective-C, it was (in my opinion) hard to know whether an Objective-C class was meant to be initialized via [[Class alloc] initWithParameters:] or [Class classWithParameters:]. Pre-ARC this did actually have meaning, but post ARC/iOS 5 it just seemed to be whatever the framework developer preferred (not to mention that [Class new] was also another option…).

When Swift combined all these forms into one common Class(parameters:) format, this greatly reduced this cognitive load. However, as outlined in the proposal, this meant that the factory pattern had to be moved out of the initializers and back into class methods. Because of this, now if you want to implement the factory pattern, you’re bringing back this same confusion from Objective-C; the client has to remember whether your class is initialized via standard Class(parameters:) syntax, or by calling a class method Class.classWithParameters(). Ultimately, I don’t believe there should be a difference between the two for the average programmer. You want an instance of the class, so you should retrieve one by calling an initializer. They don’t need to know or care whether the initializer is directly assigning to self or returning a value, as long as they get the value they need.

If we want to hide the fact that a factory method is a factory method, then we need the “assign to self’ in the initializer. Introducing a ‘factory’ keyword for that purpose seem counter productive to me.

Rien.

···

On 01 Apr 2017, at 01:35, Riley Testut via swift-evolution <swift-evolution@swift.org> wrote:

On Mar 20, 2017, at 8:07 PM, Greg Parker <gparker@apple.com> wrote:
On Mar 21, 2017, at 8:49 AM, David Rönnqvist <david.ronnqvist@gmail.com> wrote:

Beyond this, however, I think the factory initializers on protocols is one of this proposal’s biggest wins. For protocol oriented programming, it’s nice to be apply to supply a default implementation so client’s don’t need to declare their own type. However, if you come across a new codebase/framework, you might not know the difference between the specific type you’re using and the protocol itself (or even which one is which). I’ve personally encountered this many times with Apple’s frameworks, such as UIActivityItemProvider and UIActivityItemSource (which one is the protocol and which one is the type? Hard to know and remember when first using them). With factory initializers on protocol extensions, the initializer can return a private type conforming to the protocol, so again there’s no need to worry about what is the concrete type and what is the protocol.

P.S. Phase 2 End Question

I didn’t realize until today that apparently Swift 4 Phase 2 ends tomorrow. Is this true, and does that mean this is now too late to make it into Swift 4?
_______________________________________________
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution

I hope so! We'll have to wait a bit for the core team to outline Swift 5
priorities.

···

On Mon, Jun 5, 2017 at 00:24 Pranshu Goyal <pranshu.goyal@novanet.net> wrote:

Any hopes for it in future?

On 4 June 2017 at 20:40, Xiaodi Wu <xiaodi.wu@gmail.com> wrote:

No.

On Sun, Jun 4, 2017 at 10:07 Pranshu Goyal via swift-evolution < >> swift-evolution@swift.org> wrote:

Is this proposal in the pipeline for Swift 4?

On 1 April 2017 at 12:03, Adrian Zubarev via swift-evolution < >>> swift-evolution@swift.org> wrote:

First, you should fix the indent in the code samples. Second, remove
any access modifier from inside a protocol. Third, we don’t support default
implementations directly inside protocols yet, so that’s a not valid
example.

Now my personal concerns. As far as I can tell XIB files in an iOS
Project are meant for UIViewControllers in first place, but it’s a common
case that they are also used to create reusable UIViews. The downside of
that abusage is view hierarchy clustering. Most developer creating a view
of Self in Self, which smells to me like really bad code.

MyCustomView // This view is useless
   + MyCustomView
       + CustomSubview1
   + CustomSubview1 // This is probably a dead IBOutlet

In fact Xcode does not use the initializer from NSCoding to show a
live rendered view inside interface builder, instead it will call a UIViews
designated initializer init(frame:). That results that a lot of the
developer write similar code like in the following snippet:

// This pattern results in a similar view cluster like mentioned above

class MyCustomView : UIView {
    override init(frame: CGRect) {
        let view = loadSomehowFromNib()
        self.addSubview(view)
    }
}

To solve this problem we’d need some functionality of factory
initializers. I believe as proposed the factory initializer won’t solve
that problem, because everything would be still restricted to a special
initializer annotated with factory.

Personally I would want to write something like this instead.

class MyCustomView : UIView {

    override init(frame: CGRect) {

        // Instantiating from a Nib file will call `init(coder:​)` on MyCustomView
        self = loadSomehowFromNib() // assuming () -> MyCustomView

        //
        self.frame = frame
    }
}

This should resolve the clustering issue by assigning the returned
instance from the function to self and create a correct view hierarchy.

+ MyCustomView
       + CustomSubview1

--
Adrian Zubarev
Sent with Airmail

Am 17. März 2017 um 17:26:29, Riley Testut via swift-evolution (
swift-evolution@swift.org) schrieb:

Hi again everyone!

Now that Swift 4 Stage 2 proposals are being considered, I thought it
might be time to revisit this proposal and see if it might align with the
goals set forth for Swift 4.

As a quick tl;dr, this proposal describes a new "factory initializer"
that would allow you to return a value from an initializer. This would have
several benefits, as mentioned in the proposal itself as well as throughout
this mailing list. For convenience, here's a link to the proposal on
GitHub:
https://github.com/rileytestut/swift-evolution/blob/master/proposals/NNNN-factory-initializers.md

Would love to hear any more comments on this proposal, and if we feel
this is appropriate for considering for Swift 4 I'll happily re-open the
pull request!

Riley Testut

On Nov 19, 2016, at 7:45 AM, arkadi daniyelian <arkdan@icloud.com> >>>> wrote:

i would appreciate this feature.

For unexperienced developers, its often hard to recognize *when*
factory is a good fit to do the job, and how exactly approach the
implementation. I imagine having this feature built into the language may
help to choose and implement factory when its the right thing to do.

On Nov 18, 2016, at 12:23 AM, Charles Srstka via swift-evolution < >>>> swift-evolution@swift.org> wrote:

Is there any chance of reviving this? It seems to me that since this
would require Swift initializers to be implemented internally in such a way
that they can return a value (as Objective-C init methods do), it may
affect ABI stability and thus may be germane to the current stage of Swift
4 development.

Charles

On Dec 17, 2015, at 3:41 PM, Riley Testut via swift-evolution < >>>> swift-evolution@swift.org> wrote:

Recently, I proposed the idea of adding the ability to implement the
"class cluster" pattern from Cocoa (Touch) in Swift. However, as we
discussed it and came up with different approaches, it evolved into a
functionality that I believe is far more beneficial to Swift, and
subsequently should be the focus of its own proposal. So here is the
improved (pre-)proposal:

# Factory Initializers

The "factory" pattern is common in many languages, including
Objective-C. Essentially, instead of initializing a type directly, a method
is called that returns an instance of the appropriate type determined by
the input parameters. Functionally this works well, but ultimately it
forces the client of the API to remember to call the factory method
instead, rather than the type's initializer. This might seem like a minor
gripe, but given that we want Swift to be as approachable as possible to
new developers, I think we can do better in this regard.

Rather than have a separate factory method, I propose we build the
factory pattern right into Swift, by way of specialized “factory
initializers”. The exact syntax was proposed by Philippe Hausler from the
previous thread, and I think it is an excellent solution:

class AbstractBase {

public factory init(type: InformationToSwitchOn) {

     return ConcreteImplementation(type)

}

}

class ConcreteImplementation : AbstractBase {

}

Why exactly would this be useful in practice? In my own development,
I’ve come across a few places where this would especially be relevant:

## Class Cluster/Abstract Classes

This was the reasoning behind the original proposal, and I still think
it would be a very valid use case. The public superclass would declare all
the public methods, and could delegate off the specific implementations to
the private subclasses. Alternatively, this method could be used as an easy
way to handle backwards-compatibility: rather than litter the code with
branches depending on the OS version, simply return the OS-appropriate
subclass from the factory initializer. Very useful.

## Protocol Initializers

Proposed by Brent Royal-Gordon, we could use factory initializers with
protocol extensions to return the appropriate instance conforming to a
protocol for the given needs. Similar to the class cluster/abstract class
method, but can work with structs too. This would be closer to the factory
method pattern, since you don’t need to know exactly what type is returned,
just the protocol it conforms to.

## Initializing Storyboard-backed View Controller

This is more specific to Apple Frameworks, but having factory
initializers could definitely help here. Currently, view controllers
associated with a storyboard must be initialized from the client through a
factory method on the storyboard instance (storyboard.
instantiateViewControllerWithIdentifier()). This works when the entire flow
of the app is storyboard based, but when a single storyboard is used to
configure a one-off view controller, having to initialize through the
storyboard is essentially use of private implementation details; it
shouldn’t matter whether the VC was designed in code or storyboards,
ultimately a single initializer should “do the right thing” (just as it
does when using XIBs directly). A factory initializer for a View Controller
subclass could handle the loading of the storyboard and returning the
appropriate view controller.

Here are some comments from the previous thread that I believe are
still relevant:

On Dec 9, 2015, at 1:06 PM, Philippe Hausler <phausler@apple.com> >>>> wrote:

I can definitely attest that in implementing Foundation we could have
much more idiomatic swift and much more similar behavior to the way
Foundation on Darwin actually works if we had factory initializers.

On Dec 7, 2015, at 5:24 PM, Brent Royal-Gordon <brent@architechies.com> >>>> wrote:

A `protocol init` in a protocol extension creates an initializer which
is *not* applied to types conforming to the protocol. Instead, it is
actually an initializer on the protocol itself. `self` is the protocol
metatype, not an instance of anything. The provided implementation should
`return` an instance conforming to (and implicitly casted to) the protocol.
Just like any other initializer, a `protocol init` can be failable or
throwing.

Unlike other initializers, Swift usually won’t be able to tell at
compile time which concrete type will be returned by a protocol init(),
reducing opportunities to statically bind methods and perform other
optimization tricks. Frankly, though, that’s just the cost of doing
business. If you want to select a type dynamically, you’re going to lose
the ability to aggressively optimize calls to the resulting instance.

I’d love to hear everyone’s thoughts on this!

Best,

Riley Testut

_______________________________________________

swift-evolution mailing list

swift-evolution@swift.org

https://lists.swift.org/mailman/listinfo/swift-evolution

_______________________________________________

swift-evolution mailing list

swift-evolution@swift.org

https://lists.swift.org/mailman/listinfo/swift-evolution

_______________________________________________
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution

_______________________________________________
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution

--
*Pranshu Goyal*
*iOS Developer*
*tlkn*
_______________________________________________
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution

--
*Pranshu Goyal*
*iOS Developer*
*tlkn*

Any chance at a 4.1 or a 4.2 round this year?

-- E

···

On Jun 5, 2017, at 1:16 AM, Xiaodi Wu via swift-evolution <swift-evolution@swift.org> wrote:

I hope so! We'll have to wait a bit for the core team to outline Swift 5 priorities.

On Mon, Jun 5, 2017 at 00:24 Pranshu Goyal <pranshu.goyal@novanet.net <mailto:pranshu.goyal@novanet.net>> wrote:
Any hopes for it in future?

On 4 June 2017 at 20:40, Xiaodi Wu <xiaodi.wu@gmail.com <mailto:xiaodi.wu@gmail.com>> wrote:
No.

On Sun, Jun 4, 2017 at 10:07 Pranshu Goyal via swift-evolution <swift-evolution@swift.org <mailto:swift-evolution@swift.org>> wrote:
Is this proposal in the pipeline for Swift 4?

On 1 April 2017 at 12:03, Adrian Zubarev via swift-evolution <swift-evolution@swift.org <mailto:swift-evolution@swift.org>> wrote:
First, you should fix the indent in the code samples. Second, remove any access modifier from inside a protocol. Third, we don’t support default implementations directly inside protocols yet, so that’s a not valid example.

Now my personal concerns. As far as I can tell XIB files in an iOS Project are meant for UIViewControllers in first place, but it’s a common case that they are also used to create reusable UIViews. The downside of that abusage is view hierarchy clustering. Most developer creating a view of Self in Self, which smells to me like really bad code.

MyCustomView // This view is useless
   + MyCustomView
       + CustomSubview1
   + CustomSubview1 // This is probably a dead IBOutlet
In fact Xcode does not use the initializer from NSCoding to show a live rendered view inside interface builder, instead it will call a UIViews designated initializer init(frame:). That results that a lot of the developer write similar code like in the following snippet:

// This pattern results in a similar view cluster like mentioned above

class MyCustomView : UIView {
    override init(frame: CGRect) {
        let view = loadSomehowFromNib()
        self.addSubview(view)
    }
}
To solve this problem we’d need some functionality of factory initializers. I believe as proposed the factory initializer won’t solve that problem, because everything would be still restricted to a special initializer annotated with factory.

Personally I would want to write something like this instead.

class MyCustomView : UIView {
     
    override init(frame: CGRect) {
         
        // Instantiating from a Nib file will call `init(coder:​)` on MyCustomView
        self = loadSomehowFromNib() // assuming () -> MyCustomView
         
        //
        self.frame = frame
    }
}
This should resolve the clustering issue by assigning the returned instance from the function to self and create a correct view hierarchy.

+ MyCustomView
       + CustomSubview1

--
Adrian Zubarev
Sent with Airmail

Am 17. März 2017 um 17:26:29, Riley Testut via swift-evolution (swift-evolution@swift.org <mailto:swift-evolution@swift.org>) schrieb:

Hi again everyone!

Now that Swift 4 Stage 2 proposals are being considered, I thought it might be time to revisit this proposal and see if it might align with the goals set forth for Swift 4.

As a quick tl;dr, this proposal describes a new "factory initializer" that would allow you to return a value from an initializer. This would have several benefits, as mentioned in the proposal itself as well as throughout this mailing list. For convenience, here's a link to the proposal on GitHub: https://github.com/rileytestut/swift-evolution/blob/master/proposals/NNNN-factory-initializers.md

Would love to hear any more comments on this proposal, and if we feel this is appropriate for considering for Swift 4 I'll happily re-open the pull request!

Riley Testut

On Nov 19, 2016, at 7:45 AM, arkadi daniyelian <arkdan@icloud.com <mailto:arkdan@icloud.com>> wrote:

i would appreciate this feature.

For unexperienced developers, its often hard to recognize *when* factory is a good fit to do the job, and how exactly approach the implementation. I imagine having this feature built into the language may help to choose and implement factory when its the right thing to do.

On Nov 18, 2016, at 12:23 AM, Charles Srstka via swift-evolution <swift-evolution@swift.org <mailto:swift-evolution@swift.org>> wrote:

Is there any chance of reviving this? It seems to me that since this would require Swift initializers to be implemented internally in such a way that they can return a value (as Objective-C init methods do), it may affect ABI stability and thus may be germane to the current stage of Swift 4 development.

Charles

On Dec 17, 2015, at 3:41 PM, Riley Testut via swift-evolution <swift-evolution@swift.org <mailto:swift-evolution@swift.org>> wrote:

Recently, I proposed the idea of adding the ability to implement the "class cluster" pattern from Cocoa (Touch) in Swift. However, as we discussed it and came up with different approaches, it evolved into a functionality that I believe is far more beneficial to Swift, and subsequently should be the focus of its own proposal. So here is the improved (pre-)proposal:

# Factory Initializers

The "factory" pattern is common in many languages, including Objective-C. Essentially, instead of initializing a type directly, a method is called that returns an instance of the appropriate type determined by the input parameters. Functionally this works well, but ultimately it forces the client of the API to remember to call the factory method instead, rather than the type's initializer. This might seem like a minor gripe, but given that we want Swift to be as approachable as possible to new developers, I think we can do better in this regard.

Rather than have a separate factory method, I propose we build the factory pattern right into Swift, by way of specialized “factory initializers”. The exact syntax was proposed by Philippe Hausler from the previous thread, and I think it is an excellent solution:

class AbstractBase {
public factory init(type: InformationToSwitchOn) {
     return ConcreteImplementation(type)
}
}

class ConcreteImplementation : AbstractBase {

}

Why exactly would this be useful in practice? In my own development, I’ve come across a few places where this would especially be relevant:

## Class Cluster/Abstract Classes
This was the reasoning behind the original proposal, and I still think it would be a very valid use case. The public superclass would declare all the public methods, and could delegate off the specific implementations to the private subclasses. Alternatively, this method could be used as an easy way to handle backwards-compatibility: rather than litter the code with branches depending on the OS version, simply return the OS-appropriate subclass from the factory initializer. Very useful.

## Protocol Initializers
Proposed by Brent Royal-Gordon, we could use factory initializers with protocol extensions to return the appropriate instance conforming to a protocol for the given needs. Similar to the class cluster/abstract class method, but can work with structs too. This would be closer to the factory method pattern, since you don’t need to know exactly what type is returned, just the protocol it conforms to.

## Initializing Storyboard-backed View Controller
This is more specific to Apple Frameworks, but having factory initializers could definitely help here. Currently, view controllers associated with a storyboard must be initialized from the client through a factory method on the storyboard instance (storyboard. instantiateViewControllerWithIdentifier()). This works when the entire flow of the app is storyboard based, but when a single storyboard is used to configure a one-off view controller, having to initialize through the storyboard is essentially use of private implementation details; it shouldn’t matter whether the VC was designed in code or storyboards, ultimately a single initializer should “do the right thing” (just as it does when using XIBs directly). A factory initializer for a View Controller subclass could handle the loading of the storyboard and returning the appropriate view controller.

Here are some comments from the previous thread that I believe are still relevant:

On Dec 9, 2015, at 1:06 PM, Philippe Hausler <phausler@apple.com <mailto:phausler@apple.com>> wrote:

I can definitely attest that in implementing Foundation we could have much more idiomatic swift and much more similar behavior to the way Foundation on Darwin actually works if we had factory initializers.

On Dec 7, 2015, at 5:24 PM, Brent Royal-Gordon <brent@architechies.com <mailto:brent@architechies.com>> wrote:

A `protocol init` in a protocol extension creates an initializer which is *not* applied to types conforming to the protocol. Instead, it is actually an initializer on the protocol itself. `self` is the protocol metatype, not an instance of anything. The provided implementation should `return` an instance conforming to (and implicitly casted to) the protocol. Just like any other initializer, a `protocol init` can be failable or throwing.

Unlike other initializers, Swift usually won’t be able to tell at compile time which concrete type will be returned by a protocol init(), reducing opportunities to statically bind methods and perform other optimization tricks. Frankly, though, that’s just the cost of doing business. If you want to select a type dynamically, you’re going to lose the ability to aggressively optimize calls to the resulting instance.

I’d love to hear everyone’s thoughts on this!

Best,
Riley Testut
_______________________________________________
swift-evolution mailing list
swift-evolution@swift.org <mailto:swift-evolution@swift.org>
https://lists.swift.org/mailman/listinfo/swift-evolution

_______________________________________________
swift-evolution mailing list
swift-evolution@swift.org <mailto:swift-evolution@swift.org>
https://lists.swift.org/mailman/listinfo/swift-evolution

_______________________________________________
swift-evolution mailing list
swift-evolution@swift.org <mailto:swift-evolution@swift.org>
https://lists.swift.org/mailman/listinfo/swift-evolution

_______________________________________________
swift-evolution mailing list
swift-evolution@swift.org <mailto:swift-evolution@swift.org>
https://lists.swift.org/mailman/listinfo/swift-evolution

--
Pranshu Goyal
iOS Developer
tlkn
_______________________________________________
swift-evolution mailing list
swift-evolution@swift.org <mailto:swift-evolution@swift.org>
https://lists.swift.org/mailman/listinfo/swift-evolution

--
Pranshu Goyal
iOS Developer
tlkn
_______________________________________________
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution

This is another feature that I really miss, especially for Cocoa/-Touch platforms this would simplify quite a few misused patterns. For instance it's very common to see people nesting an UIView inside a CustomView where the UIView was created from a XIB file, because right now it's not possible to fine tune this pattern using a factory initializer like this:

class CustomView : UIView {
  init() {
    // Custom function that returns `CustomView` or traps
    self = instantaiteFromXib()
  }

  required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
  }
}

Maybe it's worth pushing this for Swift 5?

4 Likes

I would also love to see this. Currently, one of my projects defines a protocol instead of a class due to the need for multiple inheritance, and we ended up having to use a random top level function as the factory method since protocols don't allow static methods to be called on the protocol itself.

Would the sequence global function be make available as a factory initialiser if this were accepted?

edit: Just noticed this discussion dates back to almost a year ago, so this isn't currently up for consideration anyway…