Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Whats the difference between Enum, Structs, Classes [duplicate]

Tags:

swift

So ive been researching online and i cannot find any simple definitions for these three . I know that An Enum and a Struct can contain Properties, Initializers, and Methods and that Both data structures are also passed by 'value', but thats pretty much it...

I want to know, What is the difference between these 3 (Enum, Structs, Classes)? in the simplest definitions for each one?

like image 652
Zanlaex Avatar asked Feb 02 '16 11:02

Zanlaex


2 Answers

I think Chris Upjohn gives a rather simple yet great explanation on the topic in the Treehouse:

Enums

An enum is considered as a structured data type that can be modified without needing to change say a String or Int multiple times within your code, for example, the below shows how easy it would be to change something by accident and forget to change it somewhere else.

let myString = "test"

if myString == "ttest" {
  // Doesn't execute because "ttest" is the value assigned to "myString"
}

With an enum we can avoid this and never have to worry about changing the same thing more than once.

enum MyEnum: String {
  case Test = "test"
}

let enumValue = MyEnum.Test

if enumValue == MyEnum.Test {
  // Will execute because we can reassign the value of "MyEnum.Test" unless we do so within "MyEnum"
}

Structs

I'm not sure how much you know about the MVC pattern but in Swift, this is a common practice, before I explain how structs are useful I'll give a quick overview of MVC in Swift.

Model - struct, useful for managing large amounts of data
View - Anything that extends UIView, more often than not this is a controller you manage on the storyboard
Controller - class, typically used only for views such as UIView controllers and UITableView

Moving on a struct as I said is used for managing large amounts of data, for instance, humans are a good example as we can use a struct to manage each person in a contact list.

struct Birthday {
  var day: Int
  var month: Int
  var year: Double
}

struct Person {
  var firstName: String
  var lastName: String
  var birthday: Birthday
  var phoneNumber: String
  var emailAddress: Int
}

For each contact you have you would create a new Person object that contains basic details along with a Birthday struct for complete reusability, the benefit to using the Birthday struct is the fact we can extend it without breaking our code, for example, if we needed an easy way to format the person's birthday we can add an additional function without affecting the rest of our code.

Classes

More often than not you would only find classes bound views, when bound to a view iOS will automatically assign a new instance of the class whenever a view is called, the second time the view is called it requests the already created instance of the class.

Other uses for a class is utility helpers which you can create as singletons, this is more of an advanced concept and generally you only need to create code like this on larger applications as generally everything you need is already built-in however it's recommend if you do need additional functionality that you use an extension which allows you to add to any built-in object and create your own subscripts.


Disclaimer: The following text belongs to Chris Upjohn. I could not have explained it any better in terms of Swift (maybe in general CS terms, using other languages), therefore I did not see any point rephrasing something similar to this.


Hope it helps!

like image 104
anthonymonori Avatar answered Oct 22 '22 20:10

anthonymonori


Enum?

Enums represent a finite number of "states of being". Unlike enums in many other languages, they are not attributes of a state of being (e.g. used as a surrogate to specify one or more flags that ultimately become integers or'd together).

enum StartuUpError : ErrorType{
    case ShowStoppingBug(bugid: Int)
    case TooManyDistractions
    case NotEnoughTime
    case NotEnoughFunding(shortFall: Int)
}

Use:

enum StartuUpError : ErrorType{
    case ShowStoppingBug(bugid: Int)
    case TooManyDistractions
    case NotEnoughTime
    case NotEnoughFunding(shortFall: Int)
}
class Startup {
    var funding = 0
    var completion = 0
    var burnRate = 10000
    var week = 0

    func raiseCapital(amount: Int){
        funding += amount
    }
    func completeWork(units: Int) throws{
        week += units
        funding -= burnRate

        if funding < 0{
           throw StartuUpError.NotEnoughFunding(shortFall: funding)
        }
        if completion >= 100{
            print("Congratulations! You've been achieved! ")
        }
    }

}
let myStrtup = Startup()
myStrtup.raiseCapital(25000)

do{
    let weeklyWOrk = 20
    for _ in 1...3{
        try myStrtup.completeWork(weeklyWOrk)
        print("At week \(myStrtup.week), tried to do \(weeklyWOrk) uits of work")
    }
}catch{
    if let error = error as? StartuUpError{
        switch error{
        case  .NotEnoughFunding(let shortFall):
            print("Ran out of funding! ShortFall:\(shortFall)")
        default:
            print("Some other problem")

        }
    }
}

Struct?

struct are basically a base type. It cannot be extended, and whilst functions can be performed on it, they should only provide additional information about that type. In short it is type defined by an assembly of attributes (which may be constant or variable)

struct slidingDoor : Door{
    var isLocked : Bool = false

    func open() {
        print("Whoooshh")
    }
    func close() {
        print("whooosh")
    }
    var description : String{
        return "Smooth sliding door"
    }
}

USE :

class BankValut : Door{
    var isLocked : Bool = true

    func open() {
        if isLocked{
          print("Locked !")
        }else{
            print("Clang!")
        }

    }
    func close() {
        print("Slamm")
        isLocked = true
    }
    func unlock(combination : String){
        isLocked = false
    }
    var description: String {
        if isLocked {
            return "A bank vault that is locked"
        } else {
            return "An unlocked bank vault"
        }
    }
}

let door1 = slidingDoor()
door1.open(

)

Class?

Perhaps things get easier here. If none of the others can be used, use this one! However, I think there are some characteristics here that are important for building a good OO model that can exploit the benefits of all of these language supported types

For More detailed explanation Refer this

like image 38
iAnurag Avatar answered Oct 22 '22 20:10

iAnurag