add a public static method to a class in swift

To add a public static method to a class in Swift, you can follow these steps:

  1. Declare the method inside the class and mark it as static and public.
  2. Use the class name to call the static method from outside the class.

Here's an example code snippet:

main.swift
class MyMath {
    
    public static func multiply(number1: Int, number2: Int) -> Int {
        return number1 * number2
    }

}

let result = MyMath.multiply(number1: 2, number2: 3)
print(result) // Output: 6
212 chars
11 lines

In this example, we have created a class named MyMath with a public and static method named multiply. This method takes two integer parameters and returns their product. We can use the class name to call this method from outside the class.

In the final line of the code, we have called the multiply method with the class name and passed two integer values as parameters. The result is 6, which is the product of 2 and 3.

gistlibby LogSnag