【问题标题】:Comparing NSNumber property wrapping NS_ENUM in Swift without using rawValue在 Swift 中比较 NSNumber 属性包装 NS_ENUM 而不使用 rawValue
【发布时间】:2016-07-01 16:39:44
【问题描述】:

我们在 ObjC 中有一些执行 JSON 序列化/反序列化的现有代码。在这些数据对象的 .h 文件之一中,我们有类似的内容:

DataObject.h

@class DataObject
typedef NS_ENUM(NSInteger, FriendStatus)
{
    FriendStatusMyself = -1,
    FriendStatusNotFriends = 0,
    FriendStatusFriends = 1,
    FriendStatusPendingIncoming = 2,
    FriendStatusPendingOutgoing = 3
};

@interface DataObject : MTLModel <MTLJSONSerializing>

@property (nonatomic, strong) NSNumber *friendStatus;
// more stuff...
@end

现在这对 JSON 序列化非常有效,并且一切正常。嗯,有点。

在我的 swift 类中,我想使用 DataObject,但引用 friendStatus 作为 FriendStatus 枚举,所以我最终经常使用 .rawValue。例如

RandomClass.swift

if (dataObject.friendStatus == FriendStatus.PendingIncoming.rawValue) {
    // do something
}

这行得通,可以说这是相对较小的,但到处使用.rawValue 似乎很糟糕(tm)。有没有办法进行转换,所以 DataObject.friendStatus 是真正的 FriendStatus 枚举,我可以停止在 swift 中使用 .rawValue

不幸的是,我可以对我的模型(DataObject)进行的更改有限,因为它是现有代码。

【问题讨论】:

    标签: objective-c swift enums


    【解决方案1】:

    因为NSNumberNSInteger 不同。 NSNumber 是引用类型,而 NSInteger 是值类型,根据您的平台解析为 Int32Int64

    告诉 Swift 如何比较 NSNumberFriendStatus

    public func == (lhs: NSNumber, rhs: FriendStatus) -> Bool {
        return lhs.integerValue == rhs.rawValue
    }
    
    public func == (lhs: FriendStatus, rhs: NSNumber) -> Bool {
        return rhs.integerValue == lhs.rawValue
    }
    

    【讨论】:

    • 我喜欢这个。我通常不喜欢运算符重载,但在这种情况下,它很适合。另一件事,有没有办法让运算符重载在 switch 语句中工作?我可以将开关更改为一堆如果,但这也有点恶心。 :) 谢谢!
    【解决方案2】:

    您可以为 DataObject 类定义一个扩展,该扩展定义了一个 getter 来为您解包。

    extension DataObject {
        var friendStatusEnum: FriendStatus {
            return FriendStatus(rawValue: friendStatus.integerValue)!
        }
    }
    

    请注意,它隐式地解开枚举,这意味着如果由于某种原因 NSNumber 的值与枚举不匹配,它将崩溃。更健壮的版本会从 init 中检查 nil 并返回合理的默认值。

    【讨论】:

    • @Code Different 和这个答案都很好。但我最终使用这种方法来解决我的特定问题。使用新的friendStatusEnum意味着对我的代码库进行一些更改,但在其他方面效果很好。谢谢你们!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-09
    • 2020-03-11
    相关资源
    最近更新 更多