[swift-evolution] [Review] SE-0018 Flexible Memberwise Initialization

Matthew Johnson matthew at anandabits.com
Fri Jan 8 10:01:31 CST 2016


> On Jan 8, 2016, at 3:22 AM, Thorsten Seitz <trsfoo at googlemail.com> wrote:
> 
> 
>> Am 07.01.2016 um 20:30 schrieb Matthew Johnson via swift-evolution <swift-evolution at swift.org <mailto:swift-evolution at swift.org>>:
>> 
>> Here is an example where partial memberwise initialization would apply.  It is similar to something in a real project:
>> 
>> public class FontPicker: UIControl {
>>   public let fonts: [UIFont]
>> 
>>   public var fontSize: CGFloat = 22
>>   public var foregroundColor: UIColor = UIColor.darkGrayColor()
>>   public var backgroundColor: UIColor = UIColor.whiteColor()
>>   // A bunch of other appearance attributes here
>> 
>>   private let collectionView: UICollectionView
>>   private let layout: UICollectionViewLayout
>>   // other internal state required by the implementation
>> 
>>   public memberwise init(...) {
>>     // configure the collection view and add it as a subview
>>   }
>> }
>> 
>> A couple points are relevant here:
>> 
>> 1. Memberwise initialization is very valuable for the appearance attributes, but is useless if it exposes our implementation details.
> 
> The appearance attributes probably won’t change within an app (would be strange to have the FontPicker sometimes have this font size then that, even stranger regarding the colors) but would only be different between different apps, or at least not change alone but in concert with all other UIControls.

An example of where it would change inside the app is with light and dark appearance modes.  It may also change as the app evolves over time and the programmer might not want to hard code appearance attributes in the UI widget itself.

> So wouldn’t it be more appropriate for this example to instead use the existing UIAppearance functionality? Then the memberwise initializer would not really be needed here as configuring the appearance would not be done in the initializer.

Not everyone likes UIAppearance, especially for custom widgets.  Even if you do, it may not always be the best solution.  Sometimes it is simpler and more clear to provide appearance attributes directly.

Aside from that, this was just an example.  Similar structure often appears in view controllers where the properties that would be memberwise initialized would include data to display, etc.

Matthew

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160108/bd0f47f2/attachment.html>


More information about the swift-evolution mailing list