如何在编写重复代码时节省时间?

时间:2016-03-09 05:02:12

标签: ios xcode swift function loops

我试图在Swift(V2.1.1)中创建一个应用程序,我想知道是否可以缩短它:

    Pillar1.center = movePillarUp(Pillar1.center.x, floaty: Pillar1.center.y, pillarNumber: 1)
    Pillar2.center = movePillarUp(Pillar2.center.x, floaty: Pillar2.center.y, pillarNumber: 2)
    Pillar3.center = movePillarUp(Pillar3.center.x, floaty: Pillar3.center.y, pillarNumber: 3)
    Pillar4.center = movePillarUp(Pillar4.center.x, floaty: Pillar4.center.y, pillarNumber: 4)
    Pillar5.center = movePillarUp(Pillar5.center.x, floaty: Pillar5.center.y, pillarNumber: 5)
    Pillar6.center = movePillarUp(Pillar6.center.x, floaty: Pillar6.center.y, pillarNumber: 6)
    Pillar7.center = movePillarUp(Pillar7.center.x, floaty: Pillar7.center.y, pillarNumber: 7)
    Pillar8.center = movePillarUp(Pillar8.center.x, floaty: Pillar8.center.y, pillarNumber: 8)
    Pillar9.center = movePillarUp(Pillar9.center.x, floaty: Pillar9.center.y, pillarNumber: 9)
    Pillar10.center = movePillarUp(Pillar10.center.x, floaty: Pillar10.center.y, pillarNumber: 10)

进入某种功能或循环,这样我就不必手动复制,粘贴和输入所有数字。

1 个答案:

答案 0 :(得分:8)

如果您发现代码包含此类xxx1xxx2xxx3模式,则您知道最好使用数组来存储xxx

如果您是Swift的初学者,这就是您创建一系列支柱的方法:

let pillarArray = [Pillar1, Pillar2, Pillar3, Pillar4, Pillar5, 
    Pillar6, Pillar7, Pillar8, Pillar9, Pillar10]

然后你只需遍历数组并在每个支柱上调用movePillarUp

for (index, pillar) in pillarArray.enumarate() {
    movePillarUp(pillar.center.x, floaty: pillar.center.y, pillarNumber: index + 1)
}

那更干净了!

实际上,您根本不需要创建Pillar1Pillar10!为什么不在获得对象时将其添加到数组中?

var pillarArray = []
pillarArray.append(someMethodThatReturnsAPillar())