How do you solve this? The enformement of self
inside initializers gets in the way sometimes.
Created
June 23, 2014 17:57
-
-
Save calebd/6093259f63dee8dc935f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
class MyView: UIView { | |
// I could define this as UIPanGestureRecognizer! but that feels like the wrong solution | |
let panGestureRecognizer: UIPanGestureRecognizer | |
init(frame: CGRect) { | |
// Can't do this here because self is not initialized yet | |
panGestureRecognizer = UIPanGestureRecognizer(target: self, action: "handlePanGestureRecognizer") | |
super.init(frame: frame) | |
// Can't do this here because a `let` is required to be initialized before the super call | |
panGestureRecognizer = UIPanGestureRecognizer(target: self, action: "handlePanGestureRecognizer") | |
} | |
func handlePanGestureRecognizer(gestureRecognizer: UIPanGestureRecognizer) { | |
} | |
} |
Seems crappy but you can do this:
panGestureRecognizer = UIPanGestureRecognizer(target: nil, action: "handlePanGestureRecognizer")
OR
panGestureRecognizer = UIPanGestureRecognizer()
And then actually assign it after the super call
Its arguable that you're conflating the duties of the view with that of the view controller and swift is trying to enforce that at compile time. Given that in theory views shouldn't know much about anything other than displaying content, the correct answer may be that the configuration of the gesture recognizer should happen externally and passed into the view, if indeed the view should be responsible for it going forward.
I don't believe the other solutions will help as I think initWithTarget with a nil parameter throws an exception and @lazy would require the gesture recognizer property to be accessed rather just being set up on the view.
my 2c
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You could use @lazy for the property and initialise the property when you access it, no?