【发布时间】:2016-08-06 19:17:11
【问题描述】:
我有一个对象可以逐行输出像素(就像旧电视一样)。该对象只是将字节写入二维数组。所以有许多水平线,每条都有许多像素。这些数字是固定的:有 x 条水平线,每条线有 y 条像素。一个像素是一个由红、绿、蓝组成的结构体。
我希望此类的客户插入他们自己的对象,这些值可以写入其中,因为我希望这两个代码在 Apple 平台(存在 CALayer)上运行良好,但也适用于其他平台(例如 Linux,需要在没有 CALayer 的情况下完成渲染)。所以我想制定这样的协议:
struct Pixel
{
var red: UInt8 = 0
var green: UInt8 = 0
var blue: UInt8 = 0
}
protocol PixelLine
{
var pixels: [Pixel] { get }
}
protocol OutputReceivable
{
var pixelLines: [PixelLine] { get }
}
这些协议将在某些时候使用,例如
let pixelLineIndex = ... // max 719
let pixelIndex = ... // max 1279
// outputReceivable is an object that conforms to the OutputReceivable protocol
outputReceivale.pixelLines[pixelLineIndex][pixelIndex].red = 12
outputReceivale.pixelLines[pixelLineIndex][pixelIndex].green = 128
outputReceivale.pixelLines[pixelLineIndex][pixelIndex].blue = 66
出现两个问题:
如何要求 PixelLine 协议在数组中至少有 1280 个像素单元,而协议 OutputReceivable 在数组中至少有 720 个 PixelLine 元素?
正如我从a video 中学到的,使用泛型可以帮助编译器生成最佳代码。有没有办法让我使用泛型来生成性能更高的代码,然后使用普通协议作为类型?
【问题讨论】:
标签: arrays swift generics protocols type-constraints