【问题标题】:Conditional value (like while loop) as method parameter条件值(如 while 循环)作为方法参数
【发布时间】:2012-06-03 17:06:56
【问题描述】:

所以,我正在尝试一种有效地做到这一点的方法:

- (void)doWhile: (/*some magical type*/)condition
{
    while (condition)
    {
        // do some magical things
    }
}

虽然您的第一个建议可能是 BOOL,但请考虑以下例外情况:

[someObject doWhile: someOtherObject];
// yes, I know that I could just do (someOtherObject != nil), but
// I should be able to just use (someOtherObject), right?
// seeing as how ifs/fors/whiles can use just the object.

[someObject doWhile: [someOtherObject isValid]];
// since -isValid returns a BOOL, this will work, but it will only
// pass the value of -isValid at the time of calling to the while loop.
// if the value of -isValid changes, -doWhile: will have no idea of the change,
// whereas while() would.

使用原语_Bool 可以解决前一个问题,但后一个问题仍然存在。是否有某种方法可以像 while() 的工作方式一样评估与类型无关的参数的真实性?

【问题讨论】:

  • 这可能不是一个通用的解决方案,但在你的最后一个例子中需要重新评估对我来说是“块”。
  • 是的,这绝对是我可以接受的方式。没想到,这绝对是一个很好的后备答案。
  • @PhillipMills 我想我会选择积木。发布答案,我会接受?

标签: objective-c loops boolean truthiness


【解决方案1】:

如 cmets 中所述,传递块是一种获得所需结果的通用方法,即使更简单的方法可能适用于不需要完全动态评估的测试用例。

【讨论】:

    猜你喜欢
    • 2015-03-02
    • 2020-03-11
    • 1970-01-01
    • 1970-01-01
    • 2022-12-07
    • 2023-03-26
    • 2018-09-22
    • 1970-01-01
    • 2019-10-26
    相关资源
    最近更新 更多