gpt4 book ai didi

ios - 在 Objective-C 中访问 Swift OptionSetType

转载 作者:搜寻专家 更新时间:2023-10-30 22:23:47 24 4
gpt4 key购买 nike

在我的 Swift 类中,我为实现选项定义了一个 OptionSetType

struct FulfillmentOption : OptionSetType {
let rawValue: Int

static let Pickup = FulfillmentOption(rawValue: 1 << 0)
static let Shipping = FulfillmentOption(rawValue: 1 << 1)
static let UserShipping = FulfillmentOption(rawValue: 1 << 2)
}

然后我创建一个变量来添加/删除和读取选项。这按预期工作。

 var options: FulfillmentOption = []
options.insert(FulfillmentOption.Pickup)
options.contains(FulfillmentOption.Pickup)

但是我需要从我的一个 Objective-C 类访问 options 变量。由于 OptionSetType 未在 Objective-C 中定义,因此该变量对我的任何 Objective-C 类都不可见。

将其公开给 Objective-C 的最佳方式是什么?我应该完全停止使用 OptionSetType 吗?

我考虑过像这样创建 publicprivate 变量以在两者之间进行转换。我不喜欢这个,但这是迄今为止我想出的最好的。

private var _options: FulfillmentOptions = []
private var options: UInt {
get {
// get raw value from _options
}
set {
// set raw value to _options
}
}

有没有更优雅的方法来完成这个?我想避免编写不必要的代码。

最佳答案

不是您问题的直接答案,但您可以作为替代方案反过来工作。定义

typedef NS_OPTIONS(NSInteger, FulfillmentOption) {
FulfillmentOptionPickup = 1 << 0,
FulfillmentOptionShipping = 1 << 1,
FulfillmentOptionUserShipping = 1 << 2,
};

在 Objective-C header 中,这将被导入到 Swift 中作为

public struct FulfillmentOption : OptionSetType {
public init(rawValue: Int)

public static var Pickup: FulfillmentOption { get }
public static var Shipping: FulfillmentOption { get }
public static var UserShipping: FulfillmentOption { get }
}

更多信息可以在 "Using Swift with Cocoa and Objective-C" 中找到引用:

  • “与 C API 交互”:

Swift also imports C-style enumerations marked with the NS_OPTIONS macro as a Swift option set. Option sets behave similarly to imported enumerations by truncating their prefixes to option value names.

  • “同一项目中的 Swift 和 Objective-C”:

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:

  • ...
  • Structures defined in Swift
  • ...

关于ios - 在 Objective-C 中访问 Swift OptionSetType,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32530018/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com