0

I just want to know how may I pass an array from Swift class to Objective C class by reference. I have idea for Swift to Swift by reference using inout keyword. But as ObjC uses pointers itself as object names. How may I inform Swift to pass the object by reference Instead of Value?

Code Snipshot

Swift:

class CheckReference: NSObject {    
    class func test() {

        let array : NSMutableArray! = nil
        ViewController.change(array) //ViewController.change(&array) doesn't work
        print(array)//does not changed 
    }
}

Objective C:

 + (void)changeArray:(NSMutableArray *)array
{
    if(!array)    
        array = [NSMutableArray array];
    [array addObject:@(2)];
}

Edit: For swift it works by changing methods as: But still Objective C interaction is not working.

class func test() {
    var array : NSMutableArray! = nil
    CheckReference.passByReference(arr: &array)
    print(array ?? "nothing")//prints 2

}
class func passByReference(arr: inout NSMutableArray!)
{
    arr = NSMutableArray()
    arr.add(2)
}
9
  • Just convert it to NSMutableArray if you want to send to obj-c function Commented Mar 17, 2017 at 11:44
  • even tried that as well. Updated question Commented Mar 17, 2017 at 11:46
  • it still passes it by value. Commented Mar 17, 2017 at 11:47
  • Hm...have you tried to create the array in swift then pass it to obj-c? Your code above seems should be working though Commented Mar 17, 2017 at 11:49
  • yup. Tried. It creates another copy and the original has nothing changed in it Commented Mar 17, 2017 at 11:53

1 Answer 1

1

Okay so my guess is that when you are passing nil, you are NOT passing a pointer, since its not pointing to anything, thus your value after that, does not changed.

If you want to pass nil, you may have to change the function to return a pointer to new NSMutableArray, and assign back to the array in your swift code

Create array first in Swift and pass to Obj-c ensure the object has been created and passing proper pointer

Sign up to request clarification or add additional context in comments.

2 Comments

Solved my problem but How Objective C handles then nil Pointers and returns objects in it??? e.g. passing an NSError = nil object and get a valid memory obtained object?
NSError handling is more like inout, remember the & when you need to hook the NSError variable? Check this might help understand, for other case I think its just the different between swift and obj-c compiler against each other

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.