Skip to content

Instantly share code, notes, and snippets.

@johnlinvc
Last active May 7, 2018 03:19
Show Gist options
  • Save johnlinvc/082540939ef8acc8182a to your computer and use it in GitHub Desktop.
Save johnlinvc/082540939ef8acc8182a to your computer and use it in GitHub Desktop.
Demo how to pass array by reference in swift
//: Playground - noun: a place where people can play
import UIKit
class Foo {
class ArrayWrapper{
var array:[Bool] = [false]
subscript(index: Int) ->Bool {
get{
return array[index]
}
set(newValue){
array[index]=newValue
}
}
}
var array:[Bool]
var nsArray:NSMutableArray
var arrayWrapper:ArrayWrapper
var inoutArray:[Bool]
init(){
array = [false]
nsArray = NSMutableArray()
nsArray.addObject(false)
arrayWrapper = ArrayWrapper()
inoutArray = [false]
}
class Bar {
var array:[Bool]
var nsArray:NSMutableArray
var arrayWrapper:ArrayWrapper
init(array:[Bool], nsArray:NSMutableArray, arrayWrapper:ArrayWrapper){
self.array = array
self.nsArray = nsArray
self.arrayWrapper = arrayWrapper
}
func change(inout inoutArray:[Bool]){
self.array[0] = true
self.nsArray.replaceObjectAtIndex(0, withObject: true)
self.arrayWrapper[0] = true
inoutArray[0] = true
}
}
func change(){
var b = Bar(array: array, nsArray: nsArray, arrayWrapper: arrayWrapper)
b.change(&inoutArray)
}
}
var foo = Foo()
foo.array //[false]
foo.nsArray //[0]
foo.arrayWrapper //{[false]}
foo.inoutArray //[false]
foo.change()
foo.array //[false]
foo.nsArray //[1]
foo.arrayWrapper //{[true]}
foo.inoutArray //[true]
@sciamano89
Copy link

While an array is passed by value, a class (along with its properties) is already passed by reference. This is so convoluted. If you're going to use an enclosing custom class anyway (as opposed to switching directly to NSMutableArray, which is a reference type), all you need to do is make it hold an array, and make the class conform to the Collection protocol, and finally add the functions you'd normally use on an array -- like append( ), insert( ), remove( ), which all should call the corresponding functions on the array property.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment