2015-11-05 91 views
1

我有一个枚举如下夫特 - 嵌套枚举默认值

enum AccountForm: String { 

    case Profile 

    enum Content: String { 
     case Feedback 
     case Likes 
    } 

    enum Actions: String { 
     case Redeem 
     case Help 
    } 
} 

这代表一种形式,其中profilecontentactions是部分和病例行。

这些决心串并工作,如预期

AccountForm.Profile.rawValue返回 “档案”

AccountForm.Content.Feedback.rawValue收益 “反哺”

不过,我想AccountForm.Content.rawValue回到 “内容”

这可能吗?或者除了枚举之外还有更好的方法来实现这个吗?

+0

你在使用什么字符串值?它真的看起来像你实际上不想使用这样的枚举,我不知道什么结构会适合不知道用例,虽然 – Kametrixom

+0

@Kametrixom我创建常量字符串作为标记,同时创建窗体。个人资料,内容,操作部分和反馈,喜欢等是行。 –

回答

-3
enum Typo { 
    case Bold 
    case Normal 
    case Italic 
    case All 
} 
enum Format: CustomStringConvertible { 
    case Header(Typo) 
    case Text(Typo) 
    var description:String { 
     switch self { 
     case .Header(let value) where value != .All: 
      return "Header.\(value)" 
     case .Header(let value) where value == .All: 
      return "Header" 
     case .Text(let value) where value == .All: 
      return "Text" 
     case .Text(let value) where value != .All: 
      return "Text.\(value)" 
     default: 
      return "" 
     } 
    } 
} 

let a:Format = .Header(.Bold) 
let b:Format = .Text(.Italic) 

Format.Header(.All) // Header 
Format.Text(.Bold) // Text.Bold 
Format.Text(.All)  // Text 
+0

这种方法有什么问题? – user3441734

+0

@Eric D:你确定吗? – user3441734

2

我猜你现在得到了一个答案,但以防万一你没有尝试这个办法:

enum AccountForm : String { 
    case profile 

    enum Content: String { 
     static let rawValue = "Content" 

     case feedback = "Feedback" 
     case likes = "Likes" 
    } 

    enum Actions : String { 
     static let rawValue = "Actions" 

     case redeem = "Redeem" 
     case help = "Help" 
    } 
} 

ContentActions枚举都应该实现静态属性你想要什么。一个警告的话虽然。通过调用属性rawValue,您显然意味着返回的值在技术上不是原始值时是原始值。如果你能,我会想到一个更好的名字(也许sectionTitle?)。

其他要注意的事情。

首先,你得属性定义为static,因为它听起来像你想打电话给他们在枚举类型(例如AccountForm.Content.rawValue),而不是对单个枚举情况下(例如AccountForm.Content.feedback.rawValue)。我会让你决定在你的背景下这是否有意义。其次,当Swift 3.0到货时,对于枚举案例的推荐将是案例标签遵循lowerCamelCase命名约定,而不是在Swift 2.2中推荐的UpperCamelCase约定。

我在这里遵循了Swift 3.0的建议,但结果是显式的原始值分配是需要的,因为你将不能依靠使用隐式原始值赋值机制来指定一个带有UpperCamelCase表示的字符串这有点令人讨厌,但这些都是影响。

无论如何,希望它有帮助。