0

Since, I have started using struct, I am wondering which is best among Class and Struct for creating Shared Instances.

Class Example:

class Helper{
    func isNetworkReachable(){
        return reachability.isReachable
    }
}

Usage:

//Below taking as a Global Instance
let helperInstance = Helper()
print(helperInstance.isNetworkReachable())

In Class, as we can see that shared instance is created and it stays is memory till application terminate.

struct Example:

struct Helper{
    static func isNetworkReachable(){
        return reachability.isReachable
    }
}

Usage:

print(Helper.isNetworkReachable())

In struct, the static keyword plays the main role as it also specifies that the instance will stays in memory till application terminates.

In short, I want to know which is best, Class or struct and why?

Sohil R. Memon
  • 9,404
  • 1
  • 31
  • 57
  • @LeoDabus What does Swift class vs struct have to do with Objective-C? – rmaddy Dec 13 '16 at 04:26
  • 1
    See http://stackoverflow.com/questions/24232799/why-choose-struct-over-class – rmaddy Dec 13 '16 at 04:28
  • @rmaddy I want to know the memory status and performance, like which uses less and which is fast? – Sohil R. Memon Dec 13 '16 at 04:30
  • @rmaddy Also, as I am using `static` keyword to access directly, is that feasible or creating an object is better? – Sohil R. Memon Dec 13 '16 at 04:32
  • Your comparisons aren't the same. In your `class`, make `isNetworkReachable` a `class` method and it will be just like your `struct` and its `static` method. – rmaddy Dec 13 '16 at 04:36
  • @rmaddy Ok so writing `class` infront of every `func` behaves same as `struct` and `static`. So, now again what will be the difference between them? For that, I should see this http://stackoverflow.com/questions/24232799/why-choose-struct-over-class?noredirect=1&lq=1 right? – Sohil R. Memon Dec 13 '16 at 04:40
  • Related: http://stackoverflow.com/questions/36788169/whats-the-difference-between-struct-based-and-class-based-singletons. – Martin R Dec 13 '16 at 05:53

0 Answers0