Approximate code I need to write
@objc(OCSomeEnum)
enum SomeEnum: Int {
case c1
case c2
...
}
extension UnitySSPPlacementType { //available in swift only
...
}
I want to use some multiple values from this enum:
@objc(OCSomeClass)
class SomeClass: NSObject {
@objc
init(cases: [SomeEnum]) {
...
}
}
Problem
@objc
conflicts with [SomeEnum]
(it understands SomeEnum
only).
Note: there are similar questions but they are all about how to use swift enum one value inside objc (or vice versa). No one answers how to work with multiple values in boths languages simultaneously.
The only clue I found out:
https://developer.apple.com/documentation/uikit/uiview/1622451-animatewithduration?language=objc https://developer.apple.com/documentation/uikit/uiview/1622451-animate
Swift
: struct AnimationOptions
Objective-C:
typedef enum UIViewAnimationOptions : NSUInteger {
...
} UIViewAnimationOptions;
But how to declare custom Swift
struct which becomes enum in Objective-C
?
Solution
According to @MartinR advice:
@objc
convenience init(cases: Array<Int>) {
let pCases = cases.map { SomeEnum(rawValue: $0)! }
self.init(cases: pTypes)
}
init(cases: [SomeEnum]) { ... }
Enums
in Objective-C
are values which is different than Swift
. To complement this difference, make your enum conform to RawRepresentable
. After conformance, SomeEnum.c1
will be of type Int
having a value equal to its rawValue
.
Here's an Example:
enum SomeEnum: RawRepresentable {
case c1, c2
var rawValue: Int {
switch self {
case .c1:
return 1
case .c2:
return 2
}
}
init?(rawValue: Int) {
switch rawValue {
case 1:
self = .c1
case 2:
self = .c2
default:
return nil
}
}
}
@objc(OCSomeClass)
class SomeClass: NSObject {
@objc init(cases: [SomeEnum.RawValue]) {
}
}
let someProperty = SomeClass(cases: [SomeEnum.c1.rawValue])
Edit:
Updated Class
@objc(OCSomeClass)
class SomeClass: NSObject {
@objc convenience init(cases: [SomeEnum.RawValue]) {
self.init(enumCases: cases.map({SomeEnum(rawValue: $0)}))
}
init(enumCases: [SomeEnum?]) {
}
}
let someProperty = SomeClass(cases: [SomeEnum.c1.rawValue])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.