gpt4 book ai didi

swift - 如何(优雅地)将 Swift 枚举与关联值持久化——或者我应该避免它们?

转载 作者:可可西里 更新时间:2023-11-01 02:16:47 27 4
gpt4 key购买 nike

我被 Swift 出色的表现力所吸引,打算为每种情况使用一个带有关联值的枚举,例如:

enum PlayerStatus {
case Playing (league: Int, position: Int)
case NotPlaying (ReasonNotPlaying, LastPlayed)
}

enum ReasonNotPlaying {
case Injured
case Away
case DidntPlay
case Left
}

struct LastPlayed {
let year: Int
let position: Int
}

class Player {

var firstName: String = ""
var surname: String = ""
// etc

var status: PlayerStatus? = nil
}

但是,我需要保留包含枚举的 Player 类,而 Realm 和 CoreData 都没有任何简单的机制来执行此操作 - 可能是因为具有关联值的枚举在 Objective-C 中不可用(或者,在 Realm ,在 Android 中?)

我是否误解了枚举?我的例子可能不清楚吗?或者我怎样才能简洁地保留枚举?

有什么建议吗?

最佳答案

你是对的。目前,Realm 不支持存储 Enum。因此,没有简单的方法可以直接存储具有关联值的枚举。

我建议的解决方法如下:

将枚举值提取到属性中。然后覆盖枚举的 setter/getter 以将枚举值转换为每次设置/获取的属性。看起来太复杂了,其实使用起来很简单,照常设置/获取status属性即可。

enum PlayerStatus {
case Playing (league: Int, position: Int)
case NotPlaying (ReasonNotPlaying, LastPlayed)
}

enum ReasonNotPlaying: String {
case Injured
case Away
case DidntPlay
case Left
}

struct LastPlayed {
let year: Int
let position: Int
}

class Player: Object {
dynamic var firstName: String = ""
dynamic var surname: String = ""
// etc

private let playingLeague = RealmOptional<Int>()
private let playingPosition = RealmOptional<Int>()

private dynamic var reasonNotPlaying: String? = nil

private let lastPlayedYear = RealmOptional<Int>()
private let lastPlayedPosition = RealmOptional<Int>()

var status: PlayerStatus? {
get {
if let league = playingLeague.value,
let position = playingPosition.value {
return PlayerStatus.Playing(league: league, position: position)
} else if let year = lastPlayedYear.value,
let position = lastPlayedPosition.value,
let reason = reasonNotPlaying {
return PlayerStatus.NotPlaying(ReasonNotPlaying(rawValue: reason)!,
LastPlayed(year: year, position: position))
}
return nil
}
set {
if let newValue = newValue {
switch newValue {
case let .Playing(league, position):
playingLeague.value = league
playingPosition.value = position

reasonNotPlaying = nil
lastPlayedYear.value = nil
lastPlayedPosition.value = nil
case let .NotPlaying(reason, lastPlayed):
playingLeague.value = nil
playingPosition.value = nil

reasonNotPlaying = reason.rawValue
lastPlayedYear.value = lastPlayed.year
lastPlayedPosition.value = lastPlayed.position
}
} else {
playingLeague.value = nil
playingPosition.value = nil

reasonNotPlaying = nil
lastPlayedYear.value = nil
lastPlayedPosition.value = nil
}
}
}

override static func ignoredProperties() -> [String] {
return ["status"]
}
}

关于swift - 如何(优雅地)将 Swift 枚举与关联值持久化——或者我应该避免它们?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37564445/

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