找不到swift darwin文档

时间:2017-03-14 10:08:10

标签: ios swift darwin sqrt

我正在使用swift并拥有以下简单代码

enter image description here

我想查看“sqrt”函数是如何实现的,所以我试图点击“Darwin.C.math”链接但没有任何反应。我用谷歌搜索了“斯威夫特达尔文苹果文档”,但没有关于“达尔文”的消息。那么有人可以告诉我,我如何找到“sqrt”函数的文档?

在java中,当我单击类名或方法名时,将出现源代码文件,其中包含有关如何实现方法和类的所有详细信息。但我似乎无法对swift / xcode做同样的事情。

2 个答案:

答案 0 :(得分:2)

达尔文是Apple Open Source Projects的一部分。在那里,您可以查看macOS(例如10.14.1)和iOS(例如11.0)中的所有开源软件,以及有关Darwin and Apple's approach to implementing Unix via BSD的文档。

此外,大多数Darwin API都是UNIX规范的实现(带有some notable differences),因此只需查找许多UNIX文档站点中的任何一个即可,如下所示:

您也可以使用手册页。例如,在您的用例中,只需打开终端并输入man sqrt

SQRT(3)                  BSD Library Functions Manual                  SQRT(3)

NAME
     sqrt -- square root function

SYNOPSIS
     #include <math.h>

     double
     sqrt(double x);

     long double
     sqrtl(long double x);

     float
     sqrtf(float x);

DESCRIPTION
     The sqrt() function compute the non-negative square root of x.

SPECIAL VALUES
     sqrt(-0) returns -0.

     sqrt(x) returns a NaN and generates a domain error for x < 0.

VECTOR OPERATIONS
     If you need to apply the sqrt() function to SIMD vectors or arrays, using the following functions provided by the Accelerate.frame-
     work may give significantly better performance:

     #include <Accelerate/Accelerate.h>

     vFloat vsqrtf(vFloat x);
     vFloat vrsqrtf(vFloat x);
     void vvsqrtf(float *y, const float *x, const int *n);
     void vvsqrt(double *y, const double *x, const int *n);
     void vvrsqrtf(float *y, const float *x, const int *n);
     void vvrsqrt(double *y, const double *x, const int *n);

SEE ALSO
     math(3)

STANDARDS
     The sqrt() function conforms to ISO/IEC 9899:2011.

BSD                            December 11, 2006                           BSD

如果您更喜欢自己的风格,也可以使用在线手册页:https://www.freebsd.org/cgi/man.cgi

答案 1 :(得分:2)

运行sqrt可获得man sqrt的文档。大多数Darwin函数是桥接到Swift的C函数,并且没有在Xcode中进行记录。

但是您要求实现,这与文档完全不同。要为您提供实现,您必须拥有所有源代码,而stdlib,Foundation和Darwin之类的东西由于直接编译而不能直接提供。它们中的一些是开源的,因此您原则上可以找到源代码,但是仍然很难知道这正是您正在使用的代码。这是编译语言的典型特征,因为没有简单的方法可以对它们进行反编译。

这就是说,正如Ben所指出的那样,如果您知道从哪里看,大多数源代码都可以在各个地方使用。 sqrt(Double)是失败时的一个很好的例子,因为您可能没有想到的实现方式。它由编译器通过__builtin_sqrt直接内联。在可以直接转换为fsqrt operation的Intel处理器上,可以对其进行矢量化处理,可以在编译时对其进行评估,或者可以通过各种其他方式内联。在不同的平台上,有不同的选择。

在您的示例中,它是在编译时计算的,并且就像您编写了var result = 3.0一样进行了编码。您可以在LLVM IR输出中看到这一点:

echo "import Darwin; var result = sqrt(9.0)" | swiftc -emit-ir -O -

...
define i32 @main(i32, i8** nocapture readnone) local_unnamed_addr #0 {
entry:
  store double 3.000000e+00, double* getelementptr inbounds (%TSd, %TSd* @"$S4main6resultSdvp", i64 0, i32 0), align 8
  ret i32 0
}
...

因此,没有任何可以实现的“实现”。没有真正的sqrt功能(尽管至少某些macOS版本具有a fake one)。

也就是说,我同意将相关手册页不以某种方式导入Xcode确实令人讨厌。这样做可能要做很多工作,因为这些函数的文档是用troff编写的,要转换成Xcode使用的doc格式可能很痛苦,但是即使这样也很好。