Re: Init in Swift
Re: Init in Swift
- Subject: Re: Init in Swift
- From: Quincey Morris <email@hidden>
- Date: Sun, 04 Sep 2016 23:29:23 -0700
- Feedback-id: 167118m:167118agrif8a:167118sNOOIIdVds:SMTPCORP
On Sep 4, 2016, at 22:50 , Gerriet M. Denkmann <email@hidden> 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 (email@hidden)
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:
This email sent to email@hidden
References: | |
| >Init in Swift (From: "Gerriet M. Denkmann" <email@hidden>) |