是否有为结构设置默认值的解决方案



我解释自己:

我这样扩展UIColor:

struct MyColors {
struct blue {
static let light = UIColor(netHex: 0x6ABB72)
static let normal = UIColor(netHex: 0x6ABB72)
static let dark = UIColor(netHex: 0x6ABB72)
}
}

有没有一个解决方案可以为UIColor.MyColors.blue.normal做UIColor.MyColors.bblue?

如果您想将应用程序调整为浅色和深色模式,您甚至可以执行以下操作:
转到资产文件夹->单击左下角的加号按钮->选择"新建颜色集"->然后转到检查器并将"外观"选项设置为"任意、浅色、深色"->设置每个外观的颜色
然后您可以使用这样的颜色:

UIColor(named: <Name of your Color Set>)

您可以使用存储类型MyColors的静态属性来扩展UIColor

extension UIColor {
static let myColors = MyColors.self
}

然后访问等颜色

UIColor.myColors.blue.light

或者,您可以像一样在UIColor命名空间中声明MyColors

extension UIColor {
struct MyColors {
struct Blue {
static let light = ...

然后像这样访问它们:UIColor.MyColors.Blue.light

要近似您想要做的事情,请考虑使用一个函数返回具有给定阴影的颜色,然后使用默认参数,例如:

extension UIColor {
enum MyColor {
case blue
enum Shade { case normal, light, dark }
func shade(_ shade: Shade) -> UIColor {
switch self {
case .blue:
switch shade {
case .normal: return .init(netHex: 0x000099)
case .light:  return .init(netHex: 0x0066cc)
case .dark:   return .init(netHex: 0x000066)
}
}
}
}
static func my(_ color: MyColor, shade: MyColor.Shade = .normal) -> UIColor {
return color.shade(shade)
}
}

使用的语法略有不同:

let myBlue = UIColor.my(.blue)

作为奖励,您可以将这些添加到MyColor:

var normal: UIColor { shade(.normal) }
var light: UIColor { shade(.light) }
var dark: UIColor { shade(.dark) }

然后你可以像以前一样做UIColor.MyColor.blue.dark

然而,我建议只添加颜色本身作为UIColor扩展:

extension UIColor {
static let myBlue = UIColor(named: "blue")
static let myLightBlue = UIColor(named: "lightBlue")
static let myDarkBlue = UIColor(named: "darkBlue")
}

这甚至允许您使用缩写,如:

label.textColor = .myBlue

最新更新