使用#line获取下标中的行号

时间:2016-06-06 19:48:39

标签: swift swift2 debug-symbols

我想得到我为调试目的调用下标的行号(比如索引超出范围等):

/* 1*/   struct Collection {
/* 2*/      // this works flawlessly
/* 3*/      func getElement(index: Int, line: UInt = #line) -> Double {
/* 4*/          print(line) // 16
/* 5*/          return 0.0
/* 6*/      }
/* 7*/       
/* 8*/      // error: Default argument is only permitted for a non-curried function parameter
/* 9*/      subscript(index: Int, line: UInt = #line) -> Double {
/*10*/          print(line) // should print 17
/*11*/          return 0.0
/*12*/      }
/*13*/   }
/*14*/   
/*15*/   let c = Collection()
/*16*/   c.getElement(1)
/*17*/   c[1]

正如您所看到的,下标版本不起作用。

这种限制是否有解决方法?

1 个答案:

答案 0 :(得分:1)

我很惊讶这是不可能的!我自己测试了这个(使用Swift 2.2),我可以确认这种情况发生了。

似乎没有解决方法。它可能是也可能不是bug。如果您认为此错误是无意的,我建议您在https://bugs.swift.org处提交错误。

修改:@MartinR正确地在评论部分指出了一些documentation

  

下标可以使用任意数量的输入参数和这些输入   参数可以是任何类型。下标也可以返回任何类型。   下标可以使用变量参数和可变参数,但是   不能使用输入输出参数或提供默认参数值。

故意行为。