我是Swift的新手,有很多重复代码。例如,如何将以下代码更改为不同的功能:
示例1
if let button = view.viewWithTag(12) as? UIButton {
// change any properties of the button as you would normally do
button.isHidden = true
}
示例2
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")
我不一定会为此使用新功能。我会这样写:
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") }
Alex答案很好,但是对于新人来说,这很复杂。我建议在尝试功能编程之前学习功能的基础知识(使用.map,.filter和其他有趣的内容)。
这是一个简单的示例,您可以通过多种方式修改以更灵活的话:
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"])
我们正在做的只是使用一个变量来保存声音...您通过在字符串中键入访问不同的声音,如用法部分所示。
这是一本词典,它们非常强大。它们基于关键和价值工作。
因此,在这里我们有" 1-a"的键,值将是我们在函数中添加的捆绑包。
该函数基本上仅转换输入参数,整数和一个字符,然后将其转换为可以与捆绑包和字典一起使用的字符串。
如果您一次一次添加许多声音,则可以将其转换为数组:
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"])
这个第二个示例正是Alex所做的,他的版本使用了.map
,实际上是一个与for
循环基本相同的函数。这是一个很棒的功能,但它专注于所谓的声明性编程 - 这是很棒的 - 但通常很难学习。