Vector: Difference between revisions

1,904 bytes added ,  2 years ago
Add Swift
(Added solution for Action!)
(Add Swift)
Line 2,778:
say u*10 #: vec[30, 40]
say u/2 #: vec[1.5, 2]</lang>
 
=={{header|Swift}}==
 
{{trans|Rust}}
 
<lang>import Foundation
#if canImport(Numerics)
import Numerics
#endif
 
struct Vector<T: Numeric> {
var x: T
var y: T
 
func prettyPrinted(precision: Int = 4) -> String where T: CVarArg & FloatingPoint {
return String(format: "[%.\(precision)f, %.\(precision)f]", x, y)
}
 
static func +(lhs: Vector, rhs: Vector) -> Vector {
return Vector(x: lhs.x + rhs.x, y: lhs.y + rhs.y)
}
 
static func -(lhs: Vector, rhs: Vector) -> Vector {
return Vector(x: lhs.x - rhs.x, y: lhs.y - rhs.y)
}
 
static func *(lhs: Vector, scalar: T) -> Vector {
return Vector(x: lhs.x * scalar, y: lhs.y * scalar)
}
}
 
extension Vector where T: BinaryInteger {
static func /(lhs: Vector, scalar: T) -> Vector {
return Vector(x: lhs.x / scalar, y: lhs.y / scalar)
}
}
 
extension Vector where T: FloatingPoint {
static func /(lhs: Vector, scalar: T) -> Vector {
return Vector(x: lhs.x / scalar, y: lhs.y / scalar)
}
}
 
#if canImport(Numerics)
extension Vector where T: ElementaryFunctions {
static func fromPolar(radians: T, theta: T) -> Vector {
return Vector(x: radians * T.cos(theta), y: radians * T.sin(theta))
}
}
#else
extension Vector where T == Double {
static func fromPolar(radians: Double, theta: Double) -> Vector {
return Vector(x: radians * cos(theta), y: radians * sin(theta))
}
}
#endif
 
print(Vector(x: 4, y: 5))
print(Vector.fromPolar(radians: 3.0, theta: .pi / 3).prettyPrinted())
print((Vector(x: 2, y: 3) + Vector(x: 4, y: 6)))
print((Vector(x: 5.6, y: 1.3) - Vector(x: 4.2, y: 6.1)).prettyPrinted())
print((Vector(x: 3.0, y: 4.2) * 2.3).prettyPrinted())
print((Vector(x: 3.0, y: 4.2) / 2.3).prettyPrinted())
print(Vector(x: 3, y: 4) / 2)</lang>
 
{{out}}
 
<pre>Vector<Int>(x: 4, y: 5)
[1.5000, 2.5981]
Vector<Int>(x: 6, y: 9)
[1.4000, -4.8000]
[6.9000, 9.6600]
[1.3043, 1.8261]
Vector<Int>(x: 1, y: 2)</pre>
 
=={{header|Tcl}}==