0

I get JSON data as a result of NSURLSession.sharedSession().dataTaskWithRequest and deserialize it to AnyObject:

var error: NSError?
let jsonObject: AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments, error: &error)

I want to pass it to a completion handler for parsing jsonObject into structured data.

Question: will jsonObject be passed by reference or deep-copied? The question arises since Array and Dictionary that JSON consists of are value-type in Swift.

I found this answer to related question that says that objects inside Foundation are indeed NSArray and NSDictionary, i.e. reference types. Is it the same with JSON data?

Community
  • 1
  • 1
sumtopmus
  • 29
  • 4
  • Why is it relavent where the object came from? Why would a reference type be passed by value? `AnyObject` is a reference type. – nhgrif Jun 10 '15 at 00:31

2 Answers2

1

Class objects (AnyObject) are always passed by reference.

nhgrif
  • 61,578
  • 25
  • 134
  • 173
Duncan C
  • 128,072
  • 22
  • 173
  • 272
0
  • JSON result data consists of NSArray and NSDictionary which are reference-type. If you get result data into jsonObject which is of type AnyObject? and you passed it in completion handler then it will depends upon type of variable inside completion handler that whether it will passed by refrence or deep values will copied. If inside completion handler variable for catching jsonObject is of type AnyObject then reference will passed and if completion handler variable is of particular Array or Dictionary type then it will deeply copied jsonObject's value.
  • Also one more thing is that if your completion handler variable is of particular type then you should know the JSON result format already otherwise it will not parsed properly.
Ashvini
  • 342
  • 3
  • 11
  • Yes, but nowadays (5/2018) this is irrelevant in practice since all JSON values are value type anyway. – vadian May 09 '18 at 14:10