无区块投射(Casting nil in block)

编程入门 行业动态 更新时间:2024-10-27 15:21:03
区块投射(Casting nil in block)

我今天很快就在玩积木,我遇到了错误:

NSString *(^testBlock)(int) = ^(int option) { if (option == 1) return @"ONE"; if (option == 2) return @"TWO"; return nil; }; NSLog(@"OUTPUT: %@", testBlock(4)); Return type 'void *' must match previous return type 'NSString *' when block literal has unspecified explicit return type

因为如果不输入“1”或“2”,我真的想返回nil,所以我决定简单地使用下面的代码将最终的返回转换回NSString:

NSString *(^testBlock)(int) = ^(int option) { if (option == 1) return @"ONE"; if (option == 2) return @"TWO"; return (NSString *) nil; };

这工作得很好,我只是好奇,如果这是正确的解决方案,或者甚至不好的做法,因为我从来没有想过投射零之前?

I was just quickly playing with blocks today and I came across the error:

NSString *(^testBlock)(int) = ^(int option) { if (option == 1) return @"ONE"; if (option == 2) return @"TWO"; return nil; }; NSLog(@"OUTPUT: %@", testBlock(4)); Return type 'void *' must match previous return type 'NSString *' when block literal has unspecified explicit return type

As I really wanted to return nil if "1" or "2" were not input I decided to simply cast the final return back to an NSString using:

NSString *(^testBlock)(int) = ^(int option) { if (option == 1) return @"ONE"; if (option == 2) return @"TWO"; return (NSString *) nil; };

This works just fine, I was just curious if this was the correct solution or even bad practice as I have never thought about casting nil before?

最满意答案

这不是最好的方法。

你应该纠正第一行:

NSString *(^testBlock)(int) = ^NSString*(int option){ if(option == 1) return @"ONE"; if(option==2) return @"TWO"; return nil; };

通过这种方式,块文字具有指定的返回类型,并且错误消失。 正确。

编辑:添加对最初的错误的解释:

没有返回类型的块将具有由编译器推断的返回类型(这对函数不会发生)。 如果块中有2个不同类型的return语句(注意nil是void *),编译器无法推断返回类型并报告错误。 要解决该错误,您必须手动指定返回类型以避免编译器出现歧义。

作为一种良好的做法,除非您使用多态,否则绝不要从同一个块中返回不同的类型。

It's not the best approach.

You should correct the first line to this:

NSString *(^testBlock)(int) = ^NSString*(int option){ if(option == 1) return @"ONE"; if(option==2) return @"TWO"; return nil; };

This way the block literal has the return type specified and the error goes away. Correctly.

EDIT: Adding explanation on the initial error:

A block without a return type will have the return type inferred by the compiler (which doesn't happen with functions). When you have 2 return statements in the block with different types (note that nil is void*) the compiler can't infer the return type and reports an error. To fix that error you have to manually specify a return type to avoid ambiguity for the compiler.

As a good practice, never return different types from the same block unless you are using polymorphism.

更多推荐

本文发布于:2023-07-04 10:09:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1023089.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:区块   Casting   block   nil

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!