Reputation: 793
I'm new to swift and have a lot of repeating code. For example how would you change the following code into different functions:
if let button = view.viewWithTag(12) as? UIButton {
// change any properties of the button as you would normally do
button.isHidden = true
}
var oneAPlayer = AVAudioPlayer()
var oneBPlayer = AVAudioPlayer()
var oneCPlayer = AVAudioPlayer()
var oneDPlayer = AVAudioPlayer()
var twoAPlayer = AVAudioPlayer()
var threeAPlayer = AVAudioPlayer()
var fourAPlayer = AVAudioPlayer()
let oneASound = Bundle.main.path(forResource: "1-a", ofType: "mp3")
let oneBSound = Bundle.main.path(forResource: "1-b", ofType: "mp3")
let oneCSound = Bundle.main.path(forResource: "1-c", ofType: "mp3")
let oneDSound = Bundle.main.path(forResource: "1-d", ofType: "mp3")
let twoASound = Bundle.main.path(forResource: "2-a", ofType: "mp3")
let threeASound = Bundle.main.path(forResource: "3-a", ofType: "mp3")
let fourASound = Bundle.main.path(forResource: "4-a", ofType: "mp3")
Upvotes: 2
Views: 63
Reputation: 63137
I wouldn't necessarily use a new function for this. I would write it like so:
let soundNames = ["1-a", "1-b", "1-c", "1-d", "2-a", "3-a", "4-a"]
let sounds = soundNames.map{ Bundle.main.path(forResource: $0, ofType: "mp3") }
Upvotes: 3
Reputation: 3995
Alex answer is good, but it's pretty complicated for someone new. I would suggest learning the basics of functions before attempting functional programming (usage of .map, .filter, and other fun stuff).
Here is a simple example that you can modify in numerous ways to be more flexible if desired:
var sounds: [String:String] = [:]
func addSound(_ num: Int,_ letter: Character) {
let key = String(num) + "-" + String(letter)
sounds[key] = Bundle.main.path(forResource: key, ofType: "mp3")
}
// Usage:
addSound(1,"a")
print(sounds["1-a"])
What we are doing is using just one variable to hold the sounds in... You access your different sounds by typing in the string, as demonstrated in the usage section.
This is a dictionary, and they are very powerful. They work based on Key and Value.
So here we have key of "1-a" and the value will be the bundle that we added in the function.
The function basically just converts the input parameters, an integer and a Character, and turns it into a string that we can use with our Bundle and Dictionary.
If you want to add many sounds at one time, you can convert this to an array:
func addSounds(_ keys: [String]) {
for key in keys {
sounds[key] = Bundle.main.path(forResource: key, ofType: "mp3")
}
}
// Usage:
addSounds( ["1-a", "1-b"])
print( sounds["1-b"])
This second example is exactly what Alex did, his version used .map
which is actually a function that does basically the same thing as the for
loop. It's a great feature, but it focuses on what's called declarative programming --which is great--but generally difficult to learn when just starting out.
Upvotes: 3