10

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?

Eric Aya
  • 69,473
  • 35
  • 181
  • 253
Zanlaex
  • 111
  • 1
  • 1
  • 6
  • 2
    Actually everything – simply and detailed – is described in the Language Guide: [Classes and Structures](https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/ClassesAndStructures.html) and [Enumerations](https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Enumerations.html) – vadian Feb 02 '16 at 11:15

3 Answers3

16

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!

Iulian Onofrei
  • 9,188
  • 10
  • 67
  • 113
anthonymonori
  • 1,754
  • 14
  • 36
4

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

iAnurag
  • 9,286
  • 3
  • 31
  • 48
0
  1. enums are initialised by one of a finite number of cases, are completely defined by their case, and should always be valid instances of that case when instantiated

2.structs should be used when there is not a finite number of valid instances (e.g. enum cases) and the struct also does not form a complete definition of an object, but rather an attribute of an object

3.A class completely defines a primary actor in your object model, both its attributes and its interactions.

Classes can be extended by inheritance. Methods within class could be overloaded or implemented later.

More Here

This is an older post explaining differnce between enum and struct:

Community
  • 1
  • 1
RealityTS
  • 1
  • 4