我试图使具有关联值的枚举符合 CaseIterable、RawRepresentable。当通过 rawValue 初始化时,我可以接受关联值的一些默认值。
enum GenresAssociated: CaseIterable, RawRepresentable, Equatable {
case unknown(String)
case blues(String)
case classical(String)
// Implementing CaseIterable
typealias AllCases = [GenresAssociated]
// Enums can have no storage, but the class they are in CAN. Note 'static' in declaration
static var allCases: [GenresAssociated] = [.unknown(""), .blues(""), .classical("")]
typealias RawValue = Int
var rawValue: Int {
// MARK: This causes a crash for unknown reason
return GenresAssociated.allCases.firstIndex(where: { if case self = $0 { return true } else { return false } } ) ?? 0
}
init?(rawValue: Int) {
guard GenresAssociated.allCases.indices.contains(rawValue) else { return nil }
self = GenresAssociated.allCases[rawValue]
}
}
有没有什么方法可以在不手动切换所有情况的情况下实现它,即没有这样的代码:
typealias RawValue = Int
var rawValue: Int {
switch self {
case .unknown:
return 0
case .blues:
return 1
case .classical:
return 2
}
}
值得注意的是,非常相似的代码运行得很好,例如
enum EnumWithValue {
case one(NSString!), two(NSString!), three(NSString!)
}
let arrayOfEnumsWithValues: [EnumWithValue] = [.one(nil), .two(nil), .three("Hey")]
if let index = arrayOfEnumsWithValues.firstIndex(where: { if case .two = $0 { return true }; return false }) {
print(".two found at index \(index)") //prints ".two found at index 1"
}
我终于可以使用它了Mirror
!
var rawValue: Int {
let selfCaseName = Mirror(reflecting: self).children.first!.label!
return GenresAssociated.allCases.firstIndex(where: { (genre) in
let switchingCaseName = Mirror(reflecting: genre).children.first!.label!
return switchingCaseName == selfCaseName
})!
}
不要介意用力打开,这里很安全。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)