Search code examples
iosswiftfor-loop

How can I stop a for each loop iteration if I need to call break inside a switch in Swift?


How to stop for each loop? On return error message next loop should not run, stop the for each loop. So, it will handle sequentially error shown:

if let fields = data.keys ?? [] {
    for each in fields {
        switch each.key {
            case One:
              let errorOne =  errorValidation(id: each.id,name:each.name, keyValue: each.key)
                if errorOne.count > 0 {
                    // Stop For Each
                }
            case Two:
                let errorTwo =  errorValidation(id: each.id,name:each.name, keyValue: each.key)
                if errorTwo.count > 0 {
                    // Stop For Each
                }
            case Three:
                let errorThree =  errorValidation(id: each.id,name:each.name, keyValue: each.key)
                if errorThree.count > 0 {
                    // Stop For Each
                }
            default: break
        }
    }
}

func errorValidation(id: String, name: String, keyValue: String) -> String {
    var errorMessage = String()
    switch keyValue {
        case One:
            if name.isEmpty {
                errorMessage = "One Is Empty"
            }
        case Two:
            if name.isEmpty {
                errorMessage = "Two Is Empty"
            }
        case Three:
            if name.isEmpty {
                errorMessage = "Three Is Empty"
            }
        default: break
    }
    return errorMessage
    printVMSLog("Error \(errorMessage)") // Always Print Three IS Empty
}

Solution

  • What you are looking for is called labeled statements. You can name your loop and then you can specify which loop you would like to break:

    if let fields = data.keys ?? []{
        fieldsLoop: for each in fields {
            switch each.key {
                case One:
                  let errorOne =  errorValidation(id: each.id,name:each.name, keyValue: each.key)
                    if errorOne.count > 0 {
                        break fieldsLoop
                    }
                case Two:
                    let errorTwo =  errorValidation(id: each.id,name:each.name, keyValue: each.key)
                    if errorTwo.count > 0 {
                        break fieldsLoop
                    }
                case Three:
                    let errorThree =  errorValidation(id: each.id,name:each.name, keyValue: each.key)
                    if errorThree.count > 0 {
                        break fieldsLoop
                    }
                default: break
            }
        }
    }