phil
phil

Reputation: 1003

Can Swift func() return multiple values to an Objective-C caller?

If I have a Swift func defined thusly:

func hilo (holeSize : Int, prompt : Int) -> (ballType : Int, ballColor : Int)) {

...
return (result1, result2)

}

Is there any way to call this Swift func from an Objective-C method? I was hoping to call the func from Objective-C using an array or dictionary of sorts to receive the func result.

Can't seem to find any doco or other that discusses this topic.

Thanks.

Upvotes: 3

Views: 1294

Answers (3)

JerryZhou
JerryZhou

Reputation: 5166

By @ikmal-ezzani 's ideal. I make a implemention detail as bellow:

Swift code:

func getResult(_ input: Int) -> (previous: Int, next: Int) {
    return (previous: input - 1, next: input + 1)
}

@objc class WrapClass: NSObject {
    @objc static func getResult(_ input: Int, callback: ((_ previous: Int, _ next: Int) -> Void)) {
        let (previous, next) = YourModel.getResult(input)
        callback(previous, next)
    }
}

Object-C code:

//to use in Object-C
__block NSInteger pre = 0;
__block NSInteger next = 0;
[WrapClass getResult:10 callback:^(NSInteger preValue, NSInteger nextValue) {
    pre = preValue;
    next = nextValue;
}];

Upvotes: 1

Ikmal Ezzani
Ikmal Ezzani

Reputation: 1283

Tuples (function that returns multiple value) are not supported in Objective-C but you can use block for that.

- (void)hilo:(int)holeSize prompt:(int)prompt callback:(void (^)(ballType : Int, ballColor : Int))result {
   ...
}


[self hilo:(int)holeSize prompt:(int)prompt callback:^(ballType : Int, ballColor : Int) {
   ....
}];

Upvotes: 5

Mick MacCallum
Mick MacCallum

Reputation: 130193

You can't. You'll have to rework your Swift method to return a type that is valid in Objective-C.

From: Apple Inc. Using Swift with Cocoa and Objective-C. iBooks.

You’ll have access to anything within a class or protocol that’s marked with the @objc attribute as long as it’s compatible with Objective-C. This excludes Swift-only features such as those listed here:

  • Generics
  • Tuples
  • Enumerations defined in Swift
  • Structures defined in Swift
  • Top-level functions defined in Swift
  • Global variables defined in Swift
  • Typealiases defined in Swift
  • Swift-style variadics
  • Nested types
  • Curried functions

For example, a method that takes a generic type as an argument or returns a tuple will not be usable from Objective-C.

Emphasis mine

Upvotes: 3

Related Questions