簡體   English   中英

如何在 NSExpression 中使用條件(例如三元運算符)?

[英]How do I use conditionals (e.g. ternary operator) in an NSExpression?

我正在使用 NSExpression 來評估簡單的字符串,例如:

NSExpression(format: "1 + 1").expressionValue(with: nil, context: nil) as? Int == 2

我的一些字符串有更復雜的邏輯,我想使用三元運算符。 我嘗試使用傳統的?:語法,但出現錯誤:

NSExpression(format: "1 + 1 == 2 ? 'YES' : 'NO'").expressionValue(with: nil, context: nil)

以 NSException 類型的未捕獲異常終止

假設我唯一能改變的是字符串,有沒有辦法使用三元運算符?

是的。 不確定文檔在哪里,但我發現了一些對TERNARY函數的模糊引用。 如果你在 NSExpression 中嘗試一下,它會起作用:

NSExpression(format: "TERNARY(1 + 1 == 2, 'YES', 'NO')").expressionValue(with: nil, context: nil) as? String == "YES"

看起來格式是:

TERNARY(<predicate>, <trueValue>, <falseValue>)

如果您不想依賴(顯然)未記錄的表達式格式,那么您可以使用

init(forConditional:trueExpression:falseExpression:)

構造函數( 文檔)。 例子:

let expr = NSExpression(forConditional: NSPredicate(format: "1 + 1 == 2"),
                        trueExpression: NSExpression(forConstantValue: "YES"),
                        falseExpression: NSExpression(forConstantValue: "NO"))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM