With Swift 5, you can use one of the following methods to solve your problem.
The following Playground code example shows elementwise multiplication using SIMD4 :
let vector1 = SIMD4(1, 2, 3, 4) let vector2 = SIMD4(2, 3, 4, 5) let vector3 = vector1 &* vector2 print(vector3) // prints: SIMD4<Int>(2, 6, 12, 20)
Note that the SIMD protocol conforms to ExpressibleByArrayLiteral . This way you can initialize your vector using an array literal:
var vector1: SIMD4 = [1, 2, 3, 4] let vector2: SIMD4 = [2, 3, 4, 5] vector1 &*= vector2 print(vector1)
You can create your own type corresponding to Numeric and ExpressibleByArrayLiteral . The following Playground code example shows how to implement and use it:
struct Vector { let x, y: Int init(_ x: Int, _ y: Int) { self.x = x self.y = y } }
extension Vector: AdditiveArithmetic { static var zero: Vector { return Vector(0, 0) } static func +(lhs: Vector, rhs: Vector) -> Vector { return Vector(lhs.x + rhs.x, lhs.y + rhs.y) } static func +=(lhs: inout Vector, rhs: Vector) { lhs = lhs + rhs } static func -(lhs: Vector, rhs: Vector) -> Vector { return Vector(lhs.x - rhs.x, lhs.y - rhs.y) } static func -=(lhs: inout Vector, rhs: Vector) { lhs = lhs - rhs } }
extension Vector: ExpressibleByIntegerLiteral { init(integerLiteral value: Int) { x = value y = value } }
import Darwin extension Vector: Numeric { var magnitude: Int { // Implement according to your needs return Int(Darwin.sqrt(Double(x * x + y * y))) } init?<T>(exactly source: T) where T : BinaryInteger { guard let source = source as? Int else { return nil } x = source y = source } static func *(lhs: Vector, rhs: Vector) -> Vector { return Vector(lhs.x * rhs.y, lhs.y * rhs.x) } static func *=(lhs: inout Vector, rhs: Vector) { lhs = lhs * rhs } }
extension Vector: ExpressibleByArrayLiteral { init(arrayLiteral elements: Int...) { assert(elements.count == 2, "arrayLiteral should have exactly 2 elements") self.x = elements[0] self.y = elements[1] } }
Using:
let vector1 = Vector(1, 2) let vector2 = Vector(2, 3) let vector3 = vector1 * vector2 print(vector3) // prints: Vector(x: 3, y: 4)
let vector1: Vector = [1, 2] let vector2: Vector = [2, 3] let vector3 = vector1 * vector2 print(vector3) // prints: Vector(x: 3, y: 4)