mercredi 1 août 2018

Class function, convenience initializer extension, factory pattern. Which one is more recommended for convenient instantiation in Swift?

I'm trying to find a best way to create UI components like UILabel, UIImageView in convenience.

Class function and convenience initializer in extensions are both fine.
In addition, it's also a good way to use a factory to produce those UI components.
Let's say we have an UIHelper just for creating UI components in convenience.
The following example are three ways to create an UIColor from a hex number.

I understand UIColor is not that kind of UI Component like UILabel, let's just take it as an example. Let me know if that confuse you or you don't get my question.

class UIHelper {
    class func getColor(with hex: Int) -> UIColor {
        let r = (hex & 0xff0000) >> 16
        let g = (hex & 0x00ff00) >> 8
        let b = hex & 0x0000ff
        return UIColor(red: CGFloat(r)/255, green: CGFloat(g)/255, blue: CGFloat(b)/255, alpha: 1)
    }
}

extension UIColor {
    convenience init(from hex: Int) {
        let r = (hex & 0xff0000) >> 16
        let g = (hex & 0x00ff00) >> 8
        let b = hex & 0x0000ff
        self.init(red: CGFloat(r)/255, green: CGFloat(g)/255, blue: CGFloat(b)/255, alpha: 1)
    }

    class func colorFrom(hex: Int) -> UIColor {
        let r = (hex & 0xff0000) >> 16
        let g = (hex & 0x00ff00) >> 8
        let b = hex & 0x0000ff
        return UIColor(red: CGFloat(r)/255, green: CGFloat(g)/255, blue: CGFloat(b)/255, alpha: 1)
    }
}

The code above are doing the same thing.
I just want to know which one is more recommended and why.

Aucun commentaire:

Enregistrer un commentaire