ios – 公式数组

前端之家收集整理的这篇文章主要介绍了ios – 公式数组前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想在 xcode中使用这样的公式制作一个客观的c数组.

> x 5
> x-5
> x / 5
> x * 5

所以我可以用arrayName [i]加载一个公式并给出x的值并得到答案.有没有办法做到这一点,如果是这样的话怎么样?

解决方法

您可以使用一系列块来实现此目的.每个块将接收参数x并返回一个值,计算您的一个函数.然后,您可以选择数组的任何位置并执行它.

它将是这样的:

  1. typedef CGFloat (^MyFunction)(CGFloat); //using a typedef to ease the heavy Syntax of the blocks
  2.  
  3. MyFunction function1 = ^CGFloat(CGFloat x){
  4. return x + 5;
  5. };
  6.  
  7. MyFunction function2 = ^CGFloat(CGFloat x){
  8. return x - 5;
  9. };
  10.  
  11. MyFunction function3 = ^CGFloat(CGFloat x){
  12. return x / 5;
  13. };
  14.  
  15. MyFunction function4 = ^CGFloat(CGFloat x){
  16. return x * 5;
  17. };
  18.  
  19. NSArray *functions = @[function1,function2,function3,function4];

现在您可以访问数组的任何位置,并执行所选的块,如下所示:

  1. MyFunction myFunction = functions[3];
  2. CGFloat test = myFunction(5); //test will hold 25,because the selected block is 'x * 5'

显然,你可以为数组的任何索引更改3.当然,您可以声明上述任何其他函数,并将它们添加到数组中.

我测试过,效果很好.希望它有所帮助.

猜你在找的iOS相关文章