Swift:将两个数字相乘

时间:2020-03-30 08:50:27

标签: swift generics protocols numeric

protocol DArray: Sequence where Element: Numeric {
    var elements: [Element] { get set }
    subscript(index: Int) -> Element { get set }
    static func *(lhs: Self, rhs: Self) -> Self
}

struct Vector<Element: Numeric>: DArray {
    var elements: [Element]

    init(_ elements: [Element] = []) {
        self.elements = elements
    }

    ...

    static func *<T: DArray>(lhs: Self, rhs: T) -> Self {
        var v = lhs
        var result: Self
        for (i, element) in rhs.enumerated() {
            let e = v[i]
            let r = element * e
            // Cannot convert value of type 'Element' (generic parameter of generic struct 'Vector') to expected argument type 'T.Element' (associated type of protocol 'Sequence')
        }
        return result
    }
}

对于Numeric协议,文档说:

数字协议为进行以下运算提供了合适的基础 标量值,例如整数和浮点数。您可以 编写可对标准中的任何数字类型进行操作的通用方法 使用数字协议作为通用约束的库。

因此,我选择了数字协议作为Element类型以及T.Element的通用约束。尽管eelement都符合Numeric协议,但我无法将它们相乘(得到错误消息:无法转换类型为'Element'的值(通用的通用参数结构“向量”)到预期的参数类型“ T.Element”(协议“序列”的关联类型))。我该怎么办?

2 个答案:

答案 0 :(得分:1)

如@Sweeper所述,您只能将相同的Numeric相乘。

因此,您必须使用where子句在函数中指定它:

static func * <T: DArray> (lhs: Vector<Element>, rhs: T) -> Vector<Element> where T.Element == Element {
    let result = zip(lhs, rhs).map { lhs, rhs in
        lhs * rhs
    }
    return Vector(result)
}

答案 1 :(得分:1)

由于乘法是可交换的,因此将*的输出类型定义为操作数的任何一种都没有意义。相反,您可以允许所有DArray的元素进行初始化。

protocol DArray: Sequence where Element: Numeric {
  var elements: [Element] { get set }
  init<Elements: Sequence>(_: Elements) where Elements.Element == Element
}

extension Vector {
  init<Elements: Sequence>(_ elements: Elements) where Elements.Element == Element {
    self.init( Array(elements) )
  }
}

然后,像这样定义运算符:

extension DArray {
  static func * <Parameter1: DArray, Output: DArray>(
    dArray0: Self, dArray1: Parameter1
  ) -> Output
  where Parameter1.Element == Element, Output.Element == Element {
    multiply(dArray0, dArray1)
  }

  static func * (dArray0: Self, dArray1: Self) -> Self {
    multiply(dArray0, dArray1)
  }

  private static func multiply<Parameter0: DArray, Parameter1: DArray, Output: DArray>(
    _ dArray0: Parameter0, _ dArray1: Parameter1
  ) -> Output
  where Parameter0.Element == Parameter1.Element, Parameter1.Element == Output.Element {
    .init( zip(dArray0, dArray1).map(*) )
  }
}

这样,您可以根据需要显式键入结果,并且在需要使用隐式键入的情况下可以重载。

struct ?: DArray, IteratorProtocol {
  mutating func next() -> Int? { nil }

  var elements: [Element] = []

  init<Elements: Sequence>(_ elements: Elements) where Elements.Element == Element { }
}


( Vector() * ?([]) ) as Vector
( Vector() * ?([]) ) as ?
( ?([]) * Vector() ) as Vector
( ?([]) * Vector() ) as ?

let vector: Vector = ( Vector() * ?([]) )
let ?: ? = ( ?([]) * Vector() )

Vector([1]) * Vector()