我最近开始在 Ruby 中使用 Ick 的“andand”,这样我就可以比以前更轻松地遍历嵌套集合。
是否有针对 Objective-C 的这个惯用法的版本在任何地方实现?
最佳答案
我不是 Ruby 程序员,所以我可能遗漏了一些微妙的东西,但看起来 andand 使它使您可以安全地链接方法调用,即使一个方法调用可能返回 nil。这是内置在 Objective-C 中的,因为在 nil 上调用方法(实际上正确地称为发送消息到)是安全且完全可以接受的。发送给 nil 的消息总是返回 nil,并且基本上是空操作。在 Objective-C 中这很好:
id foo = [someObject objectByDoingSomething]; // foo might be nil
id bar = [foo objectByDoingSomethingElse];
// If foo is nil, calling objectByDoingSomethingElse is essentially
// a no-op and returns nil, so bar will be nil
NSLog(@"foo: %@ bar: %@", foo, bar);
因此,这也很好,即使 objectByDoingSomething 可能返回 nil:
id foo = [[someObject objectByDoingSomething] objectByDoingSomethingElse];
来自 The Objective-C Programming Language :“在 Objective-C 中,向 nil 发送消息是有效的——它在运行时根本不起作用。”该文档包含有关在 Objective-C 中调用 nil 方法的确切行为的更多详细信息。
关于objective-c - 是否有用于 Objective-C 的 'andand' monad 版本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8696745/