【发布时间】:2015-09-17 20:54:58
【问题描述】:
我通常在 Objective-C 中使用断言来断言一个值。在调试版本中,我断言是为了停止程序的执行并检查我的假设是否不正确。但是,在生产构建中,我找到了一种安全失败的方法,以尽量减少对用户的影响。我通过创建一个宏来实现这一点,该宏将 NSAssert 封装在 if 语句中,该语句还执行我想在生产中作为故障安全运行的代码。例如:
我将使用的断言宏:
#define AssertTrueOrExecute(condition, action) \
if (!condition) { \
NSAssert(testCondition, @"Condition failed"); \
action; \
}
在我的应用程序的某个地方,我会有这样的东西:
- (void)someMethod
{
BOOL testCondition = ...
// Ensure the testCondition is true before proceeding any further
AssertTrueOrExecute(testCondition, return);
// Potentially unsafe code that never gets executed if testCondition is false
}
- (void)someReturningMethod
{
BOOL testCondition = ...
// Ensure the testCondition is true before proceeding any further
AssertTrueOrExecute(testCondition, return @"safe string");
// Potentially unsafe code that never gets executed if testCondition is false
}
由于我无法定义像 Swift 中提到的那样的宏,有没有办法具有相同的行为?那我将如何为我的 AssertTrueOrExecute 宏提供一个 Swift 等效项?
更新:
为了进一步解释这个问题,如果我使用的是 Swift,我目前会这样写:
func someMethod () {
let testCondition : Bool = ...
// Ensure the testCondition is true before proceeding any further
if (!testCondition) {
assert(testCondition);
return;
}
// Potentially unsafe code that never gets executed if testCondition is false
}
所以问题更多的是如何将带有断言的 if 语句以与我有 Objective-C 宏的类似方式包装,以便我可以断言或提前返回?
更新 2:
另一个例子是在函数中返回一些东西,例如:
func someReturningMethod () -> String {
let testCondition : Bool = ...
// Ensure the testCondition is true before proceeding any further
if (!testCondition) {
assert(testCondition);
return "safe string";
}
// Potentially unsafe code that never gets executed if testCondition is false
return "some other string"
}
【问题讨论】:
标签: objective-c swift macros