Swift Arrays

In this forum members can discuss topics about specific programming languages.
Post Reply
vamsikal3
Posts: 55
Joined: Sat Oct 01, 2016 8:25 am

Swift Arrays

Post by vamsikal3 » Sun Sep 30, 2018 7:07 am

I am a little bit of a programming languages enthusiast. I try to solve PE problems (same problems multiple times) in different languages to get a feel for the languages. I have used Haskell, C++, Java, Scala, Kotlin, Rust to solve PE problems. My personal experience is that Kotlin and Rust stand out as good languages to solve PE problems.

Now, I am planning on solving/re-solving a few PE problems in Swift. While learning Swift, I found out that Arrays are value-types in Swift, i.e. they will be passed by value (copied?) to functions. The threads I have read on StackOverflow do not give a clear picture as to how Arrays are passed to functions in Swift. So, I came up with a simple rule-of-thumb: Always wrap an Array inside a reference type and provide the accessor/mutators to the wrapped Array in the wrapper class (see below):

Code: Select all

class MeaningfulName {
  // accessor
  func subscript(indx : Int) -> Int {
    return arr[indx]
  }
  
  // Implement a mutator, if needed.
  func set_value(indx : Int, value : Int) {
    arr[indx] = value
  }
  var arr : [Int]()
}
Is this a reasonable way of making sure Arrays are never copied, when passed to functions? Are there any fellow Swift enthusiasts here to provide some information on how best to deal with Arrays in Swift?

Thanks,
vamsikal3
my friend key --> 990813_OZPwQtCjkD6KlvxirOoTSZxccMFsuw1L
Image

Post Reply