【问题标题】:Calling objective c method with enum as argument in swift在swift中以枚举作为参数调用objective c方法
【发布时间】:2018-08-24 17:27:19
【问题描述】:

我正在尝试在 swift 中使用带有枚举作为参数的客观 c 方法。参数的值是根据 swift 枚举变量设置的。

Swift 枚举

enum SecurityType: Int {

    case pushNotification = 0
    case touchId = 1
    case faceId = 2
}

我在目标 c 文件中的枚举看起来像

typedef NS_ENUM(NSUInteger, ScreenType) {
TouchID = 1,
FaceID = 2,
ConsentApproval = 3,
VerifyMyIdentity = 4 };

我的快速代码是

let screenType: ScreenType = self.biometricType == .touchId ? .touchID : .faceID

guard let newVC = MyViewController.init(screenType: screenType) else { return }

在上述方法中,biometricType变量是swift枚举类型。

这是我的初始化方法

-(instancetype)initWithScreenType:(screenType *)type {

self = [超级初始化];

  if (self) {
     UIStoryboard *passcodeStoryBoard = [UIStoryboard  storyboardWithName:passcode bundle:nil];
     self = [passcodeStoryBoard  instantiateViewControllerWithIdentifier:@"AuthenticationViewController"];
     self.screenType = type;
     return self;
  }

返回零; }

我在 init 方法上遇到错误

无法将“EnumType”类型的值转换为预期的参数类型“UnsafeMutablePointer!”

有人知道这背后的原因吗?

【问题讨论】:

  • 你能发布init方法是如何定义的吗,这就是故事的一半。
  • -(instancetype)initWithScreenType:(screenType *)type { => -(instancetype)initWithScreenType:(screenType)type { 没有*
  • 我在这里犯了多么愚蠢的错误。非常感谢@Larme,它解决了我的问题。

标签: objective-c swift enums


【解决方案1】:

首先,self.biometricType 的类型是UnsafeMutablePointer。 您不能将UnsafeMutablePointer 类型设置为枚举ScreenType

其次,你应该像这个例子一样使用完整的枚举名称来访问 obj-c 枚举。

let screenType: ScreenType = ScreenType.TouchId

【讨论】:

  • 我明白你的意思,但有没有使用目标类型枚举的解决方法。我也不能更改目标 c 枚举,因为它是遗留代码的一部分。
  • 您是否使用 obj-c 标头创建了一个桥接头文件以在 swift 中使用 obj-c 文件?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多