Search code examples
swiftcompiler-errorspredicate

Checking many strings in one go in a single (if) statement


I'm trying to check 10 strings not to be empty to run my script. How can I break it down reasonably to stay within one function? My script relies on all of those to be true and it's quite long, so I can't interrogate each one individually. It works with 6 names or less. But from name 7 - 10 I get an error when building my app.

if (name[1] != "") && (name2[1] != "") && (name3[1] != "") && (name4[1] != "") && (name5[1] != "") && (name6[1] != "") && (name7[1] != "") && (name8[1] != "") && (name9[1] != "") && (name10[1] != "")

I get this error:

The compiler is unable to type-check this expression in reasonable time; try breaking up the expression into distinct sub-expressions


Solution

  • Having numbered variable names like that is a big red flag. They should be in an array.

    What you're looking for is Sequence.allSatisfy(_:), which returns true iff all members in a sequence satisfy the provided predicate:

    let names = [name[1], name1[1], name2[1], ... name10[1]] // this is madness, get rid of these numbered variables
    
    let allNamesArentEmpty = names.allSatisfy { !$0.isEmpty }
    if allNamesArentEmpty { ... }