如何重复函数Swift的一部分

时间:2017-11-16 15:14:33

标签: ios swift repeat

仍在学习基础知识。我有一个函数,其中有一个块,需要重复而不再调用整个函数。这是如何在Swift中完成的?

func connected(to peripheral: Peripheral) {
    let cwConnection = CWStatusBarNotification()
    cwConnection.display(withMessage: "Ring Connected", forDuration: 3)

    BluejayManager.shared.getHeliosInfo { (success) in
        if success {
            // Go on
        } else {
            // Repeat this block (BluejayManager.shared.getHeliosInfo)
        }
    }
}

2 个答案:

答案 0 :(得分:3)

嘿Riyan,这很简单。这是您的问题的解决方案。只需将块放在其他小方法中,当你只需要调用那个块调用那个小函数时。

func connected(to peripheral: Peripheral) {
    let cwConnection = CWStatusBarNotification()
    cwConnection.display(withMessage: "Ring Connected", forDuration: 3)

    self.callBluejayManagerShared() // Call of block from method
}

func callBluejayManagerShared(){
    BluejayManager.shared.getHeliosInfo { (success) in
        if success {
            // Go on
        } else {
            // Repeat this block (BluejayManager.shared.getHeliosInfo)
            self.callBluejayManagerShared()
        }
    }
}

现在,当您只想调用阻止时,您只需要调用self.callBluejayManagerShared()方法。 希望这能帮到你

答案 1 :(得分:2)

您可以使用repeat - whileBluejayManager.shared.getHeliosInfo检查success作为休息条件:

repeatGetInfo: repeat {
    BluejayManager.shared.getHeliosInfo 
    { (success) in
            if success 
            {
                // do your stuff.
                break repeatGetInfo
            } else 
            {
                continue repeatGetInfo
            }
        }
} while true

希望这有帮助