Swift 2.0 按值传递

Swift 2.0 passing by value

我刚刚进入 Swift 中的结构,我有一个非常基本的问题,我在其他地方找不到答案。如果您定义一个函数,其中 returns 一个结构的新实例,将创建多少个实际对象?

在下面的例子中,CGRectMake构造了一个结构体实例,returns它给这个函数,然后调用者收到另一个副本。这是否意味着以下代码行将创建 3 个结构实例并立即丢弃 2 个?

Client:

var rect = makeNormalFacetTextRect();

API:

class func makeNormalFacetTextRect() -> CGRect {
    return CGRectMake(new_x, new_y, new_width, new_height);
}

此外,如果我以这种方式构造我的方法(我经常在调试时这样做),是否会引入另一个副本(总共 4 个)?

class func makeNormalFacetTextRect() -> CGRect {
    var newRect = CGRectMake(new_x, new_y, new_width, new_height);

    return newRect; 
}

来自Swift documentation

The behavior you see in your code will always be as if a copy took place. However, Swift only performs an actual copy behind the scenes when it is absolutely necessary to do so. Swift manages all value copying to ensure optimal performance, and you should not avoid assignment to try to preempt this optimization.

我想这回答了你的问题。

来自 Apple 的 documentation

Structures and Enumerations Are Value Types

A value type is a type whose value is copied when it is assigned to a variable or constant, or when it is passed to a function.

在我看来这意味着

class func makeNormalFacetTextRect() -> CGRect {
    var newRect = CGRectMake(new_x, new_y, new_width, new_height);

    return newRect; 
}

将创建 2 个结构。初始化 newRect 时将创建一个。第二个将在您将 newRect 复制到您的变量时创建:

var rect = makeNormalFacetTextRect();

原代码比较有意思:

class func makeNormalFacetTextRect() -> CGRect {
    return CGRectMake(new_x, new_y, new_width, new_height);
}

当你打电话时

var rect = makeNormalFacetTextRect();

将创建 1 个或 2 个结构。我倾向于相信 1 会被创建,因为我认为 Swift 优化得足够好,可以将上面的代码翻译成:

var rect = CGRectMake(new_x, new_y, new_width, new_height)

此外,文档中提到 Swift 优化了某些值类型(例如字符串、字典等)的复制。在我看来,这也意味着结构的复制也将得到优化。

在任何情况下,上述两个代码都不能产生超过 2 个结构