How to call [self new] in Swift

Here is the UIView extension written in ObjectiveC to easily create a view for using Auto-layout:

 +(id)autolayoutView { UIView *view = [self new]; view.translatesAutoresizingMaskIntoConstraints = NO; return view; } 

it calls [self new] , so any subclass of UIView can use this method. How can I achieve this in Swift?

+6
source share
3 answers

OK, this seems to be the solution. The type must have a required initializer with the correct list of parameters (in this case there are no parameters).

 class SubView: UIView { override required init() { super.init() } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } class func autolayoutView() -> UIView { var view = self() view.setTranslatesAutoresizingMaskIntoConstraints(false) return view } } 
+5
source

Inspired by Gregory Higley, I think the solution is here:

 extension UIView{ class func autolayoutView() -> UIView { var view = self() view.setTranslatesAutoresizingMaskIntoConstraints(false) return view } } 

Update for Swift2.1:

 extension UIView{ class func autolayoutView() -> UIView { let view = self.init() view.translatesAutoresizingMaskIntoConstraints = false return view } } 
+1
source

Although both Karl and Gregory Higley have the right solutions, including the observation that self () should use the required init, I would like to post a more general example:

 class Human { var gender = String() required init() { self.gender = "any" } class func newHuman() -> Human { return self() } } class Man : Human { required init() { super.init() self.gender = "male" } } var someMan = Man.newHuman() println(someMan.gender) // male 
+1
source

Source: https://habr.com/ru/post/982166/


All Articles