How to create a static class in Swift?

I am looking to create a static VectorCalculator class. Perhaps this function should just be placed in my Vector class (similar to the NSString method -stringByAppendingString in Obj-C) ... and if you think that ... let me know.

In any case, I want to add a couple of static functions to the static VectorCalculator class. It will calculate the "point product" and return the vector. Another function is likely to "calculate and return the angle between two given vectors."

A) Someone will go this way of creating a static class for this or

B) should you 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 main classes Vector Vector u .

What is the advantage of transition A or B?

If you think B is for future reference, how would you create the entire static class in Swift?

+6
source share
3 answers

If you correctly understood that you are interested in type methods in case A. You specify type methods by writing a static keyword before the func keyword methods. Classes can also use the class keyword to allow subclasses to override the superclass implementation of this method. (WITH)

  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 the benefits of B, it depends on the tasks you are solving. If you want the original vectors to be unmodified, it’s more convenient to use option A. But I think you could provide both types of functionality.

+6
source

how would you create an entire static class in Swift?

static means not an instance, so I would make it a structure without an initializer:

 struct VectorCalculator { @available(*, unavailable) private init() {} static func dotProduct(v: Vector, w: Vector) -> Vector { ... } } 
+5
source

I think you are looking for class functions? Perhaps your answer can be found here. How to declare a class level function in Swift?

 class Foo { class func Bar() -> String { return "Bar" } } Foo.Bar() 

In Swift 2.0, you can use a static keyword instead of a class. But you have to use a static keyword for structs and a class keyword for classes

// Editing just saw that I misunderstood your question correctly

+1
source

All Articles