在单个 (if) 语句中一次性检查多个字符串
Checking many strings in one go in a single (if) statement
我正在尝试检查 运行 我的脚本中的 10 个字符串是否为空。我怎样才能合理地分解它以保持在一个功能内?我的脚本依赖于所有这些都是真实的,而且它很长,所以我不能单独询问每一个。它适用于 6 个或更少的名称。但是从名称 7 - 10 开始,我在构建我的应用程序时遇到了错误。
if (name[1] != "") && (name2[1] != "") && (name3[1] != "") && (name4[1] != "") && (name5[1] != "") && (name6[1] != "") && (name7[1] != "") && (name8[1] != "") && (name9[1] != "") && (name10[1] != "")
我收到这个错误:
The compiler is unable to type-check this expression in reasonable
time; try breaking up the expression into distinct sub-expressions
像这样对变量名进行编号是一个大危险信号。它们应该在一个数组中。
您要查找的是 Sequence.allSatisfy(_:)
,其中 returns true
当且仅当序列中的所有成员都满足提供的谓词:
let names = [name[1], name1[1], name2[1], ... name10[1]] // this is madness, get rid of these numbered variables
let allNamesArentEmpty = names.allSatisfy { ![=10=].isEmpty }
if allNamesArentEmpty { ... }
我正在尝试检查 运行 我的脚本中的 10 个字符串是否为空。我怎样才能合理地分解它以保持在一个功能内?我的脚本依赖于所有这些都是真实的,而且它很长,所以我不能单独询问每一个。它适用于 6 个或更少的名称。但是从名称 7 - 10 开始,我在构建我的应用程序时遇到了错误。
if (name[1] != "") && (name2[1] != "") && (name3[1] != "") && (name4[1] != "") && (name5[1] != "") && (name6[1] != "") && (name7[1] != "") && (name8[1] != "") && (name9[1] != "") && (name10[1] != "")
我收到这个错误:
The compiler is unable to type-check this expression in reasonable time; try breaking up the expression into distinct sub-expressions
像这样对变量名进行编号是一个大危险信号。它们应该在一个数组中。
您要查找的是 Sequence.allSatisfy(_:)
,其中 returns true
当且仅当序列中的所有成员都满足提供的谓词:
let names = [name[1], name1[1], name2[1], ... name10[1]] // this is madness, get rid of these numbered variables
let allNamesArentEmpty = names.allSatisfy { ![=10=].isEmpty }
if allNamesArentEmpty { ... }