0

I'v implemented a static TimeMonitor class in Java that look like this:

    public class SomeClass {
        private static ArrayList<String> _myList = new ArrayList<>();

        public static void add(String str) {
            _myList.add(str);
        }

        public static int getCount() {
            return _myList.length;
        }
    }

and I'm using it like this:

SomeClass.add("my string")

so when I'll call

int count = SomeClass.getCount()

The value of count will be 1

I do I implement the equivalent code in Swift 3?

I've found this question: How can I create a static class in Swift?, but I can't find a reference to an example that shows not only static methods but also saving static data as demonstrated in the Java example

Community
  • 1
  • 1
Guy Segal
  • 953
  • 1
  • 12
  • 24

1 Answers1

1

Immediately off the top of my head, maybe something like...

public class SomeClass {
    internal static var myList: [String] = []

    public static var count: Int {
        return myList.count
    }

    public static func add(_ str: String) {
        myList.append(str)
    }
}

Then you could use it something like..

SomeClass.add("Hello")
let count = SomeClass.count

Equally, you could use a struct, since you can't really override anything, for example...

public struct SomeClass {
    internal static var myList: [String] = []

    public static var count: Int {
        return myList.count
    }

    public static func add(_ str: String) {
        myList.append(str)
    }
}
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366