Ну, похоже, что векторы float3
и float4
уже имеют реализацию map
(через реализацию протокола Sequence
/ Collection
).
Так что единственное, что нам нужно сделать, это реализовать Collection
для матриц:
extension simd_float3x3: Collection {
public var startIndex: Int {
return 0
}
public var endIndex: Int {
return 3 // for `sims_float4x4` it would be 4, number of columns
}
public func index(after i: Int) -> Int {
return i + 1
}
}
и теперь мы можем сделать это:
let matrix: simd_float3x3 = initCodeForTheMatrix()
matrix.flatMap { $0 }
Вы можете объявить этот удобный подпротокол, чтобы не вводить одинаковые startIndex
и index(after:)
для всех типов матриц:
public protocol SIMDCollection: Collection {}
extension SIMDCollection {
public var startIndex: Int {
return 0
}
public func index(after i: Int) -> Int {
return i + 1
}
}
// And use it like this:
extension simd_float3x3: SIMDCollection {
public var endIndex: Int {
return 3
}
}
extension simd_float4x4: SIMDCollection {
public var endIndex: Int {
return 4
}
}
extension simd_float3x2: SIMDCollection {
public var endIndex: Int {
return 3
}
}
// etc
Это может пойти еще дальше, потому что endIndex
будет одинаковым для всех simd_floatX_Y
с одинаковыми X
и любыми Y
. Даже не имеет значения, если это *float*
или *double*
или что-то еще.