How can I create a static class in Swift?

chris P picture chris P · Jan 25, 2016 · Viewed 30.9k times · Source

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?

Answer

Cœur picture Cœur · Mar 3, 2017

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 {
        ...
    }
}