I'm looking to create a static class called VectorCalculator. Perhaps this function should just be placed in my Vector class (similar to NSString's --stringByAppendingString
method in Obj-C)... and if you think that... let me know.
Anyway I want to add a couple of static functions to a static class called VectorCalculator. It will calculate the 'dot product' and return a Vector. Another function will likely be to 'calculate and return the angle between two given vectors'.
A) Would anyone go this route of creating a static class for this or
B) should I just add these functions as instance functions of the Vector class such as... public func dotProductWithVector(v: Vector) -> Vector
and public func angleWithVector(v: Vector) -> Double
. And then both of these argument vectors v will be applied to the Vector classes main Vector u.
What's the benefit of going either A or B?
If you think B, just for future reference, how would you create an all static class in Swift?
If I've understood you correctly you are interested in Type methods in case A. You indicate type methods by writing the static keyword before the method’s func keyword. Classes may also use the class keyword to allow subclasses to override the superclass’s implementation of that method. (c)
struct Vector {
var x, y, z: Int
}
class VectorCalculator {
static func dotProductOfVector(vec1: Vector, withVector vec2: Vector) -> Vector {
let newX = //calc x coord;
let newY = //calc y coord;;
let newZ = ////calc z coord;;
return Vector(x: newX,y: newY, z: newZ);
}
}
let vec1 = Vector(x:1, y:2, z:3)
let vec2 = Vector(x:4, y:5, z:6)
let v = VectorCalculator.dotProductOfVector(vec1, withVector: vec2)
As for benefits of B it depends on tasks you solve. If you want to left original vectors unmodified it's more convenient to use A variant. But I think you could provide both types of functionality.
how would you create an all static class in Swift?
static
means no instance, so I would make it a struct with no initializer:
struct VectorCalculator {
@available(*, unavailable) private init() {}
static func dotProduct(v: Vector, w: Vector) -> Vector {
...
}
}
I think what you looking for are class functions?
Maybe your Answer can be found here.
How do I declare a class level function in Swift?
class Foo {
class func Bar() -> String {
return "Bar"
}
}
Foo.Bar()
In Swift 2.0 you can use the static keyword instead of class. But you should use static keyword for structs and class keyword for classes
//Edit just saw that i properly misunderstood your question