协议中的结构化属性

时间:2017-01-12 15:25:52

标签: swift

说我有

protocol Theme {
    var headerTextColor: UIColor { get }
    var footerTextColor: UIColor { get }

    var headerImage: UIImage { get }
    var footerImage: UIImage { get }
}

struct DarkTheme: Theme {
    var headerTextColor: UIColor { return ... }
    var footerTextColor: UIColor { return ... }

    var headerImage: UIImage { return ... }
    var footerImage: UIImage { return ... }
}

struct LightTheme: Theme {
    var headerTextColor: UIColor { return ... }
    var footerTextColor: UIColor { return ... }

    var headerImage: UIImage { return ... }
    var footerImage: UIImage { return ... }
}

实现此协议访问属性的实例如下

lightTheme.headerTextColor
darkTheme.footerImage

我想要实现的是以某种方式 结构 这些属性,以便最后的代码片段看起来像

lightTheme.color.headerText
darkTheme.image.footer

1 个答案:

答案 0 :(得分:3)

  

我想要实现的是以某种方式结构这些属性   最后一个片段看起来像

lightTheme.color.headerText
darkTheme.image.footer

您已经在此请求中自己强调了“结构”:只需创建自定义结构即可生成您喜欢的属性树。 E.g。

/* set these properties to 'var' in case you plan to
   mutate them beyong initialization */

struct Colors {
    let headerText: UIColor
    let footerText: UIColor
    // ...
}

struct Images {
    let header: UIImage
    let footer: UIImage
    // ...
}

正如您在问题的评论中已经指出的那样,除了公共属性的值之外,类型 DarkThemeLightTheme之间似乎没有区别。这意味着您可能只想定义单个Theme类型,并且具有此类型的实例来描述不同的主题(例如,黑暗和明亮的主题)。

使用上述帮助结构,例如:

struct Theme {
    let color: Colors
    let image: Images
    // ...
}

// two Theme instances
let darkTheme = Theme( /* initialize with some "dark" theme 
                          values for the member properties
                          of Theme */ )

let lightTheme = Theme( /* some "light" theme */ )

// access subproperties of each theme (which are as initialized)
darkTheme.color.headerText
lightTheme.image.footer

/* if you want to mutate these themes on the fly, simply set
   the instance properties of Theme and the help structures to
   mutables ('var') */