On Sep 4, 2016, at 22:50 , Gerriet M. Denkmann <gerr...@mdenkmann.de> wrote:
> 
> I really want “onlyKnownBySubclass” to be a constant (i.e. let instead of var)

There’s an easy way if you can declare both classes in the same file. Then, you 
can just declare the instance variable like this:

>       private(set) var onlyKnownBySubclass: Int


(That’s Swift 2. For Swift 3, use “fileprivate” instead of “private”.) In this 
case, “onlyKnownBySubclass” looks like a “let” property outside that one source 
file.

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
> {
>       init(some: Int)
>       {
>               super.init(some: some) { $0 + 5 }
>       }
> }
> 
> let a = SubClass(some:11)
> a.someFunction()      //      prints: “Should never be zero: 27”

This closure “{ $0 + 5 }” is shorthand for the longer form:

        { 
                valuePassed in 
                return valuePassed + 5 
        }

The idea is that the superclass contributes values by parameters to the closure 
(just one, knownBySuperclass, in this case), and the subclass contributes the 
rest of the expression (which could make use of other subclass properties, 
since this closure occurs after the property initialization phase of the 
subclass init.

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.

_______________________________________________

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