swiftgenericsfactory

In a swift static var extension, how to or can you access and return the concrete class?


Consider

extension UIView {
    
    static var Trick: UIIView {
        let v = UIView()
        v.backgroundColor = .yellow
        return v
    }
}

hence addSubview(UIView.Trick) and so on.

However

private lazy var yellowLabel: UILabel = {
    let v = UILabel.Typical
    v.font = U.systemFont(ofSize: 200)
    return v
}()

of course is wrong. Is there a way to ......

extension V where V is one of the UIView types {
    
    static var Trick: V {
        let v = " V "()
        v.backgroundColor = .yellow
        return v
    }
}

Is there a way?


Solution

  • The type of the computed property in a class extension can be Self to specify the concrete type on which the property is called. Also Self() creates an instance of that concrete type:

    extension UIView {
        static var Trick: Self {
            let v = Self()
            v.backgroundColor = .yellow
            return v
        }
    }
    

    Now

    private lazy var yellowLabel: UILabel = {
        let v = UILabel.Trick // <-- Type of `v` is UILabel
        v.font = .systemFont(ofSize: 200)
        return v
    }()
    

    compiles and works as expected.