Copy Creation when we pass primitive type such as Int to a Swift Function.

When we pass a input to swift function it is passed as a constant, so does copy gets created or not here?

public func Test (_ pValue : Int) {
     print (pValue)
}

let x : Int = 2

Test (x)

does copy gets created or not here?

Yes, the int is copied.

(Why do you ask? What alternative behaviour can you imagine?)

If you want to pass a reference, to be able to modify the parameter, you have to use inout.

public func Test (_ pValue : inout Int) {
    print ("on call", pValue)
    pValue += 10
}

var x : Int = 2  // Must be a var ; 
// with let, would get a compile error: 
// Cannot pass immutable value as inout argument: 'x' is a 'let' constant

Test (&x)
print ("after call", x)

You get:

on call 2
after call 12

+1 to both endecotp and Claude31.

Another thing to keep in mind here is that Int is a small struct and Swift will typically pass that around in CPU registers. In that case the concept of ‘copy’ starts to break down. Sure, at the language level Swift is making a copy, but at the CPU level it’s just moving between registers.

Beyond that, in the code snippet you posted the x value will almost certainly never be realised in memory and the Test(_:) function will be inlined, so that whole thing will resolve down to:

print(2)

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

Copy Creation when we pass primitive type such as Int to a Swift Function.
 
 
Q