Hi,
I am constructing a generic struct type of matrix and trying to provide different options for initialization.
protocol MatrixContainer {
associatedtype Element
init(_ rows:UInt, _ columns:UInt, with defaultVal:Element)
subscript(rowId:Int) -> [Element] { get }
subscript(rowId:Int, colId:Int) -> Element { get }
}
And a struct conforming to the MatrixContainer protocol
public struct Matrix<Element: Numeric & Comparable > : MatrixContainer {
var mat: Array<Array<Element>>
...
public init(_ rows:UInt, _ columns:UInt, with defaultVal:Element) {
self.rows = rows
self.columns = columns
self.mat = Array.init(repeating: Array.init(repeating: defaultVal, count: Int(columns)), count: Int(rows))
}
.....
Now I want the default initialization for Int, Double, Float and UInt I am specializing as follows.
extension Matrix where Element == Double {
public init(_ rows:UInt, _ columns:UInt) {
self.init(rows, columns, with: 0.0)
}
}
extension Matrix where Element == Float {
public init(_ rows:UInt, _ columns:UInt) {
self.init(rows, columns, with: 0.0)
}
}
extension Matrix where Element == Int {
public init(_ rows:UInt, _ columns:UInt) {
self.init(rows, columns, with: 0)
}
}
extension Matrix where Element == UInt {
public init(_ rows:UInt, _ columns:UInt) {
self.init(rows, columns, with: 0)
}
}
This works. But I'm not happy with the way I am generalizing it. I feel it is too verbose.
Is there a better way to specialize the init functions with cleaner and nicer syntax?