Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bridging an array of enums from Swift to Objective-C

Since Swift 1.2 it's been possible to automatically convert enums in Swift to Objective-C. However, as far as I can tell, it is not possible to convert an array of enums. Is this true?

So, this is possible:

@objc public enum SomeEnumType: Int {
    case OneCase
    case AnotherCase
}

But this is not:

public func someFunc(someArrayOfEnums: Array<SomeEnumType>) -> Bool {
    return true
}

Can anyone verify this? And how would you recommend working around this? One approach would be to have two method declarations e.g:

// This will not automatically get bridged.
public func someFunc(someArrayOfEnums: Array<SomeEnumType>) -> Bool {
    return true
}

// This will automatically get bridged.
public func someFunc(someArrayOfEnums: Array<Int>) -> Bool {
    return true
}

But this is polluting the Swift interface. Any way to hide the second function declaration for any Swift consumers?

like image 429
Steffen D. Sommer Avatar asked May 26 '15 08:05

Steffen D. Sommer


People also ask

Can enum extend another enum Swift?

So it is not possible to have a certain Enum extend and inherit the cases of another enum.

Should enums be capitalized Swift?

The name of an enum in Swift should follow the PascalCase naming convention in which the first letter of each word in a compound word is capitalized. The values declared in an enum — up , down , left and right — are referred to as enumeration case.

Can an enum have a function Swift?

Finally, let's take a look at how enum cases relate to functions, and how Swift 5.3 brings a new feature that lets us combine protocols with enums in brand new ways. A really interesting aspect of enum cases with associated values is that they can actually be used directly as functions.

What is enum in Objective C?

Objective-C Enumerators allow variables to be declared with a predefined list of valid values, each of which is assigned a name that can be used when setting the variable. This has the advantage of making the code easier to read and understand.


1 Answers

It seems, we cannot expose Array<SomeEnumType> parameter to Obj-C even if SomeEnumType is @objc.

As a workaround, how about:

@objc(someFunc:)
func objc_someFunc(someArrayOfEnums: Array<Int>) -> Bool {
    return someFunc(someArrayOfEnums.map({ SomeEnumType(rawValue: $0)! }))
}

func someFunc(someArrayOfEnums: Array<SomeEnumType>) -> Bool {
    return true
}
like image 176
rintaro Avatar answered Sep 22 '22 02:09

rintaro