希望更好地理解Swift函数

时间:2016-12-16 04:59:52

标签: swift function

我是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")

2 个答案:

答案 0 :(得分:3)

我不一定会为此使用新功能。我会这样写:

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") }

答案 1 :(得分:3)

亚历克斯回答很好,但对于一个新人来说这很复杂。我建议在尝试函数式编程之前学习函数的基础知识(使用.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"])

我们正在做的只是使用一个变量来保存声音......您可以通过输入字符串来访问不同的声音,如使用部分所示。

这是一本字典,它们非常强大。他们的工作基于Key和Value。

所以在这里我们有#34; 1-a"而值将是我们在函数中添加的包。

该函数基本上只转换输入参数,整数和字符,并将其转换为我们可以与Bundle和Dictionary一起使用的字符串。

如果您想一次添加多个声音,可以将其转换为数组:

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循环基本相同的函数。它是一个很棒的功能,但它专注于所谓的声明性编程 - 这很棒 - 但是刚开始时通常很难学习。