> On 5 Sep 2016, at 13:29, Quincey Morris <quinceymor...@rivergatesoftware.com> 
> wrote:
> 
> On Sep 4, 2016, at 22:50 , Gerriet M. Denkmann <gerr...@mdenkmann.de> wrote:
> 
> If you can’t do that, you can do it with a closure, assuming the places of 
> definition aren’t more complicated than in your code. Something like this:
> 
>> class SuperClass
>> {
>>      let knownBySuperclass: Int
>>      let onlyKnownBySubclass: Int
>>      
>>      init(some: Int, calc: (known: Int) -> Int)
>>      {
>>              knownBySuperclass = some * 2
>>              onlyKnownBySubclass = calc (known: knownBySuperclass)
>>      }
>>      
>>      final func someFunction() -> Void
>>      {
>>              print("Should never be zero: \(onlyKnownBySubclass)")
>>      }
>> }
>> 
>> final class SubClass: SuperClass
>> {
            var localConstantDependingOnSuper: Int      //      should really 
be a constant
>>      init(some: Int)
>>      {
                        localConstantDependingOnSuper = 0       //      all 
must be set before calling super
>>              super.init(some: some) { $0 + 5 }

                        localConstantDependingOnSuper = knownBySuperclass + 27
> 
>>      }
>> }
>> 
>> let a = SubClass(some:11)
>> a.someFunction()     //      prints: “Should never be zero: 27”

This trick with the closure is rather neat. I would never have come up with it. 
Thanks for telling me!
But what to do about localConstantDependingOnSuper?


> More globally, this sort of thing is not terribly idiomatic for Swift, 
> because you’re trying to hide things that could get exposed other ways, for 
> example, by “hostile” subclassing. The Swift-ier way would be to use a 
> protocol instead of (or in addition to, but preferably instead of) the 
> superclass. The protocol would “force” the subclass to define its own 
> “onlyKnownBySubclass” locally.

I do not think this would work for me. There are several subclasses and the 
superclass contains lots of functions (some of which are overwritten by 
subclasses).
If the superclass becomes a protocol then all this code had to be duplicated in 
each subclass.


Another problem:
Super → SubA and SubB.
SubA → SubA1 and SubA2
SubB → SubB1 and SubB2

Both SubA1 and SubB1 have identical functions. As have  SubA2 and SubB2.
Multiple inheritance would be a solution here; but neither Objective-C nor 
Swift can do this (and I don’t like C++).

Current solution: cut and paste and trying to keep both versions in sync.
Anything better?

Kind regards,

Gerriet.



_______________________________________________

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Reply via email to