Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to invoke [self new] in Swift

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

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

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

like image 891
duan Avatar asked Feb 08 '15 12:02

duan


People also ask

How do you declare yourself in Swift?

Swift allows omitting self when you want to access instances properties. When a method parameter has the same name as an instance property, you have to explicitly use self. myVariable = myVariable to make a distinction.

What does .self mean in Swift?

In Swift, the self keyword refers to the object itself. It is used inside the class/structure to modify the properties of the object. You can assign initial values to properties in the init() method via self.

How does self work in Swift?

In Swift self is a special property of an instance that holds the instance itself. Most of the times self appears in an initializer or method of a class, structure or enumeration. The motto favor clarity over brevity is a valuable strategy to follow.

Why do we write self in Swift?

“self” as an Object in Swift This self is a reference to the current object (“instance”) of a class (or struct), within that class. You can work with self as if it's a variable or object within the class (or struct), that is the class (or struct). It's an essential concept of Object-Oriented Programming (OOP).


1 Answers

OK, this appears to be the solution. The type must have a required initializer with the correct parameter list (in this case 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
    }
}
like image 141
Gregory Higley Avatar answered Nov 09 '22 08:11

Gregory Higley