Unpacking stack objects (e.g. structs) using "if let"

It is rather a matter of optimizing the Swift compiler for an additional stack of the Swift object (for example, struct) and "if let".

In Swift, "if let" provides you with syntactic sugar for working with options. What about the structures that live on the stack? As a C ++ programmer, I would not present an unnecessary copy of the stack object, especially to check its presence in the container. Is the structure copied with all its members recursively every time you use "if let" or is the fast compiler optimized to create a local variable by reference or other tricks?

For example, we have this structure packaged in optional:

struct MyData{
    var a=1
    var b=2
    //lots more store....

    func description()->String{
        return "MyData: a="+String(a)+", b="+String(b)
    }
}
var optionalData:MyData?=nil
optionalData=MyData()

, , optionalData var , , ?

if let data=optionalData{//is data copy or reference?
    println(data.description())
}
+4
1

, , optionalData var , , ?

. let .

" x = y" x ( ), ..

let x = y
x.foo = bar
y.foo // => bar

. let - mutable. Swift let x = y, y , no-op.

, , y:

y.foo = bar
let x = y
y.foo = baz
x.foo // => bar

, , . " ", , let.

:

if let data=optionalData{//is data copy or reference?
    println(data.description())
}

, , ​​ . , , ; , :

if (optionalData != nil)
{    
    println(optionalData!.description())
}
+3

Source: https://habr.com/ru/post/1543505/


All Articles