How to group extension methods in Swift

Issue #11

Swift allows us to define more methods on existing class using extension.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
extension UIView {

func shake() {

}

func fade() {

}

func centerIn(anotherView: UIView) {

}
}

If you ‘re afraid of the naming conflict, you can prefix your methods, like

1
2
3
view.abc_shake()
view.abc_fade()
view.abc_centerIn(anotherView: containerView)

Or a better way, reverse it 💃 , like

1
2
3
view.animation.shake()
view.animation.fade()
view.layout.centerIn(anotherView)

This way, no more conflict and we make it clear that shake() and fade() belongs to animation category
Actually, animation and layout are properties in UIView extension. This may cause naming conflict, but the number of them is reduced

This is how it works

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
extension UIView {

struct Animation {
let view: UIView

func shake() {
// Shake the view
}

func fade() {
PowerfulAnimationEngine.fade(view)
}
}

var animation: Animation {
return Animation(view: self)
}

struct Layout {
let view: UIView

func centerIn(anotherView: UIView) {

}
}

var layout: Layout {
return Layout(view: self)
}
}

Comments