Lawrence413 Lawrence413 - 1 year ago 47
Swift Question

Swift class array with enum

I just read the Apple Documentation regarding

s but I'm still somewhat confused.

Say I have the class named Employee. I want the class employee to have an array of tasks (I guess best option is [String]). But I want each task to have a status that's either

I could have another property inside
called taskName, but I think it's easier to just make the

Here's what I thought so far to write:

class Employee {
class Tasks: Array { // Or [String], I have no idea
enum Status {
case Complete
case Incomplete

var tasks: Tasks

init?() {
self.tasks = Tasks()

// Then I guess Employee.tasks[0].Status should work

I know that it's most likely wrong. So how should I do it?

Answer Source

Here is the simple way how you can do.

//Employee Class with Array of Task
class Employee {
    var tasks: [Task]
    init(tasks: [Task]) {
        self.tasks = tasks

//Task Class has the status
class Task {
    var status:Status
    var taskName: String
    init(status: Status, taskName: String) {
        self.status = status
        self.taskName = taskName

//Status is an enum
enum Status {
    case Complete
    case Incomplete

And here is the simple test code...

let task1 = Task(status: Status.Complete, taskName: "First Task")
let task2 = Task(status: Status.Incomplete, taskName: "Second Task")
let employee = Employee(tasks: [task1, task2])

print(employee.tasks[0].status) //Prints -->> Complete
print(employee.tasks[1].taskName)//Prints -->> Second Task