Array pass by value by default & thread-safety

Viewed 814

Say I have a class which has an Array of object Photo:

class PhotoManager {
  fileprivate var _photos: [Photo] = []

  var photos: [Photo] {
      return _photos
  }
}

I read one article which says the following:

By default in Swift class instances are passed by reference and structs passed by value. Swift’s built-in data types like Array and Dictionary, are implemented as structs.

Meaning that the above getter returns a copy of [Photo] array.

Then, that same article tries to make the getter thread-safe by refactoring the code to:

fileprivate let concurrentPhotoQueue = DispatchQueue(label: "com.raywenderlich.GooglyPuff.photoQueue",
                                                       attributes: .concurrent)
  fileprivate var _photos: [Photo] = []
  var photos: [Photo] {
    var photosCopy: [Photo]!
    concurrentPhotoQueue.sync {
        photosCopy = self._photos
    }
    return photosCopy
  }

The above code explictly make a copy of self._photos in getter.

My questions are:

  1. If by default swift already return an copy (pass by value) like the article said in the first place, why the article copy again to photosCopy to make it thread-safe? I feel myself do not fully understand these two parts mentioned in that article.

  2. Does Swift3 really pass by value by default for Array instance like the article says?

Could someone please clarify it for me? Thanks!

2 Answers
Related