如何实现用户可以添加多个自定义 if 语句?
例如,假设有一个名为 x 的给定变量,其给定值为 8。 用户看到 x = 8 并有一个添加 if 语句的按钮。他单击按钮并可以插入触发事件的条件(假设它打印“Hello World”)。所以他在字段中输入“x < 100”,结果为真。因此打印了“Hello World”。 再次单击该按钮后,他可以添加另一个条件,假设“x < 7”也是如此。因为两个条件都为真,所以仍然打印“Hello World”。 我想你明白了我的问题,尽管我缺乏词汇。 那么我如何设法让用户添加未定义数量的条件,这些条件将在打印“Hello World”之前进行检查? 我知道的唯一解决方案是限制可能的条件数量,并检查每个条件是否为空/条件说明了什么。
非常感谢!
最佳答案
除非你想构建一门完整的语言,否则你必须弄清楚你将在此处允许的确切操作。
例如<
的操作和 >
和 ==
, 基本上所有的比较操作(<=
和 >=
以及)都可以通过以下方式实现:
/* your X variable, might be var if you desire to change */
let x = 12
/* the array of conditions the user entered */
var conditions : [(((Int, Int) -> Bool), Int)] = []
/* some user input - read as e.g. "x > 2"*/
conditions.append((<, 100))
conditions.append((>, 2))
conditions.append((==, 12))
/* you evaluate all conditions in the following way */
let eval = conditions.map { $0(x, $1) }
let allTrue = !eval.contains(false)
/* allTrue would be true in this case because 12 < 100 && 12 > 2 && 12 == 12 */
现在您的“艰巨”工作是将用户输入解释为一些 condition
.但这并不太难,您只需要映射 "<"
的文本输入即可。致实际运算符(operator)<
.
你可以调整上面的代码来处理Double
而不是 Int
如果你像你需要的那样摔倒很容易。 但是你必须意识到 float 的不准确性以及检查相等性时出现的问题(感谢@dfri 指出了这一点)。
关于将条件与 or
结合起来,有点困难。而不是 and
以上代码的作用以及您目前在问题中描述的内容。
只是因为我喜欢闭包:下面是整个输入读取和解析:
func getOperator(str: String) -> ((Int, Int) -> Bool)? {
switch str {
case "<":
return (<)
case ">":
return (>)
case "==":
return (==)
case "<=":
return (<=)
case ">=":
return (>=)
default:
return nil
}
}
func parseUserInput(str:String) -> (((Int, Int) -> Bool), Int) {
var input = str as NSString
input = input.stringByReplacingOccurrencesOfString(" ", withString: "")
//let variable = input.substringToIndex(1) // in case you want more than one variable, but that will have to change the entire setup a bit
// this has to be this "ugly" to incorporate both 1 char and 2 char long operators
let operato = input.substringFromIndex(1).stringByTrimmingCharactersInSet(NSCharacterSet.alphanumericCharacterSet())
let number = input.substringFromIndex(operato.lengthOfBytesUsingEncoding(NSASCIIStringEncoding) + 1)
if let number = Int(number), op = getOperator(operato) {
return (op, number)
}
return ((<, 999999)) // need some error handling here
}
conditions.append(parseUserInput("x > 123"))
您甚至可以使用来自 ">"
的普通旧字典映射,而不是使用函数来解析运算符。至 (>)
等
关于javascript - 动态评估用户添加的 If 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34566538/