首页 > 解决方案 > Return to beginning of a function in Swift

问题描述

So I've following code running in Xcode 12 with SwiftUI:

public func giveCard() -> String {
    var randomNumber = Int.random(in: 0..<maxCards-1)

    if saveRandoms.contains(randomNumber) {
        print("Already exist - generate new number")
    } else {
        let actualCard = questionCard[randomNumber]

        saveRandoms.add(randomNumber)
        return actualCard
        print("Schicke frage")
    }
    return "No question-card left"
}

The code creates random numbers between 0 and the variable maxCards. When a questionCard fitting to the random number which was created was used, the random number is stored in the array saveRandoms.

To avoid showing the same question the if-statement checks if the new created random number is already in the array saveRandoms. If not, the fitting question will be shown.

If the number was already used it should generate a new number until finding a unused one. And that's my problem. How can I return to the beginning of my function to check again and again if the random number was already used?

标签: swiftfunctionreturn

解决方案


我认为最好的解决方案是将逻辑置于while循环中,并在找到新数字时完成执行。


推荐阅读