有没有办法将枚举关联值类型设置为默认值,而不是为每个情况定义它,如下所示?
enum Device {
case phone(String)
case watch(String)
case tablet(String)
}
我想避免用(String)
重复自己答案 0 :(得分:2)
在这种情况下,可能更容易定义它:
enum DeviceType {
case phone
case watch
case tablet
}
struct Device {
var type: DeviceType
var name: String
... init, etc.
}
然后你可以彼此独立地处理类型和字符串,因为如果每个枚举的情况都有一个字符串,那么听起来这个字符串可能与枚举值没有直接关系。
答案 1 :(得分:1)
如果您对文字感到满意,那么为什么不使用rawValues
而不是关联的文字:
enum DeviceType: String {
case phone = "iPhone X"
case watch = "Longines"
case tablet = "Samsung"
// Only literals can serve as raw values, so next line won't work:
// case notebook = NSLocalizedString("Any personal computer", comment: "")
}
如果您需要相同类型的可变关联值,则可能会发现字典很有用。
// Add CaseIterable conformance protocol to obtain DeviceType.allCases
enum DeviceType: String, CaseIterable {
case phone = "iPhone X"
case watch = "Longines watch"
case tablet = "Samsung tablet"
// Only literals can serve as raw values, so next line won't work:
// case notebook = NSLocalizedString("Any personal computer", comment: "")
// if you don't want any other vars involved you can add a method to enum
func localizedName() -> String {
return NSLocalizedString(self.rawValue, comment: "")
}
}
// Create your perfect dict for enum (You'll have to manually add strings to translation)
let deviceTypeLocalized = Dictionary(uniqueKeysWithValues: zip(DeviceType.allCases, DeviceType.allCases.map{ NSLocalizedString($0.rawValue, comment: "") }))
// use (or even change) "associated" values with the power of dicts
let localizedWatchName = deviceTypeLocalized[.watch]
// this is how you get your "associated" value from enum without any external dictionaries, without looking it up.
let localizedTabletName = DeviceType.tablet.localizedName()