0

I would like to check my understanding of the inout parameter. Assume this adt() function is going to be called millions of times on a very very large array, lets say 10mb array. Adding the inout parameter in this example, will prevent the 10mb array being duplicated in memory millions of times over and over again? Is that correct?

import Foundation

func adt(_ d: inout [UInt8], _ i:UInt8) {
    d.append(i)
}

var d:[UInt8] = []
adt(&d,1)
adt(&d,2)
adt(&d,3)

I understand that inout is the correct way to allow parameters outside the function to be modified, but I cant find documentation on how the memory is managed in this situation.

Jay
  • 19,649
  • 38
  • 121
  • 184
  • 1
    Maybe [this question](https://stackoverflow.com/questions/34486052/when-to-use-inout-parameters) could be helpful. – Joakim Danielson Jun 12 '22 at 12:02
  • https://docs.swift.org/swift-book/ReferenceManual/Declarations.html#ID362 – vacawama Jun 12 '22 at 13:10
  • Sure, this is better than passing an array by value... But why not encapsulate it in a class instead: `class ArrayHandler { private var d: [UInt8] = []; func adt(_ i: UInt8) { d.append(i) }` - no copying big arrays, and if tomorrow you need to make any changes - for example make an array thread-safe, you have better chance to do so if it's encapsulated. – timbre timbre Jun 12 '22 at 17:13
  • Thanks @jjquirckart I was only intending to communicate some sample code that demonstrated usage of `inout`. I am not sure if the real code can be refectory this way, I will see what I can do, thanks! – Jay Jun 12 '22 at 22:02

0 Answers0