这是一个为UInt8
,red
和green
的{{1}}颜色组成的颜色提供足够好的亮度表示的属性。
blue
我希望它看起来像这样,但它没有编译:
var luma: UInt8 {
return UInt8(
[(red, 54), (green, 183), (blue, 19)].reduce(0){
let (color, eightBitWeight) = $1
return $0 + Int(color) * eightBitWeight
} >> 8
)
}
我们可以更接近,没有比前者更多的代码吗?
答案 0 :(得分:4)
我希望
[(red, 54), (green, 183), (blue, 19)].reduce(0) {
(luma, let (color, eightBitWeight)) in
return luma + Int(color) * eightBitWeight
}
但是我遇到了编译错误......
这里和我一样近。
[(red, 54), (green, 183), (blue, 19)].reduce(0) {
(luma, item: (color: Int, eightBitWeight: Int)) in
return luma + Int(item.color) * item.eightBitWeight
}
我不确定red
,green
,blue
的类型是什么,所以我制作了Int
。
答案 1 :(得分:2)
我认为你原来的解决方案:
let red = 1, green = 2, blue = 3
var luma: UInt8 {
return UInt8(
[(red, 54), (green, 183), (blue, 19)].reduce(0){
let (color, eightBitWeight) = $1
return $0 + Int(color) * eightBitWeight
} >> 8
)
}
非常好,因为它是最小的和显式的(虽然我同意元组解包语法可能更简单),但如果你想要紧凑而不是显式输入,那么你可以使用默认的参数名称:
let red = 1, green = 2, blue = 3
[(red, 54), (green, 183), (blue, 19)].reduce(0) {
$0 + Int($1.0) * $1.1
}
但这更难阅读。如果是我的代码,我会使用较短的变量名称,并调整原始格式:
let r = 1, g = 2, b = 3
return reduce([(r, 54), (g, 183), (b, 19)], 0) { let v = $0, (color, weight) = $1
return v + color * weight
}
答案 2 :(得分:0)
作为元组的替代,你考虑过枚举吗?
enum RGBColor {
case Red(UInt32)
case Green(UInt32)
case Blue(UInt32)
func toLumaComponent() -> UInt32 {
switch self {
case let .Red(weight): return weight << 16
case let .Green(weight): return weight << 8
case let .Blue(weight): return weight
}
}
}
[RGBColor.Red(54), .Green(183), .Blue(19)].reduce(UInt32(0)) {
luma, color in
return luma | color.toLumaComponent()
}
甚至是一个简单的功能?
func RGBColorToLuma(# red: UInt32, # green: UInt32, # blue: UInt32) -> UInt32 {
return red << 16 | green << 8 | blue
}
RGBColorToLuma(red: 54, green: 183, blue: 19)