# Show and hide views

I have some buttons in my class that show or hide two views (by setting their alpha property to either 0 or 1) when the user taps on them. I have written a function that uses the tag property of the sender of the button (which is passed to the function by default) to identify which view to show or hide:

@IBAction func showOrHideView(sender: AnyObject) {
UIView.animateWithDuration(0.5, animations: {
switch sender.tag {
case 1:
case 2:
self.viewTips.alpha = self.viewTips.alpha == 1 ? 0 : 1
default:
break
}
})
}


How can I make this code cleaner?

First, I would consider making a reusable method on UIView to encapsulate the alpha toggle:

extension UIView {

func animateToggleAlpha() {
UIView.animateWithDuration(0.5) {
self.alpha = self.alpha == 1 ? 0 : 1
}
}
}


That way, you have a nicely encapsulated and reusable function for toggling the alpha of any view. You have already shown that you need it for two views of your app, so you will likely need it in other places.

Once you have the method above, there are two ways to make the code cleaner. If there are a bunch of views that need this behavior, and that is all the buttons are supposed to do, then you can put the views in an array and index them by the button's tag.

@IBOutlet var views: [UIView]!

@IBAction func showHideButtonTapped(sender: UIButton) {
views[sender.tag].animateToggleAlpha()
}


If you need to do more than simply animate the views and what you need to do is different depending on which button is tapped, then I would rather see multiple methods...

@IBAction func sketchpadButtonTapped(sender: UIButton) {