0

I'm trying to create an extension to UIView with a static initializer (for example like new). In my old Objective-C projects I would create a Category with the following implementation:

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

But I can't find a way to do this in swift. I thought about creating a normal class function:

class func autolayout() {
    let view = self.init()
    view.translatesAutoresizingMaskIntoConstraints = false

}

.. but what should be the return type?

smeshko
  • 1,184
  • 13
  • 27

1 Answers1

1

When using extensions on class functions you should use Self as this implies it is the object is type of self.

Self can be used on class functions and in protocols.

//: Playground - noun: a place where people can play

import UIKit

extension UIView {

  class func autoLayout() -> Self {
    let view = self.init()
    view.translatesAutoresizingMaskIntoConstraints = false
    return view
  }

}

let view = UIView.autoLayout()
Oliver Atkinson
  • 7,970
  • 32
  • 43