marksjack
marksjack

Reputation: 59

Swift - retrieve at Index within a Directory

In Swift is it possible to retrieve / remove an element in a Dictionary using it's index, not a key value? In this example I'm attempting to create a "to do" list where I can eventually access all the tasks assigned to an individual. But I would also like to remove an element (task) by index.

In the code below how can I remove the second task "wash dishes" by index not using a key value. I was hoping to call this func with something like: taskMgr.removeTaskByIndex(1)

Any additional explanation or advice is helpful as I'm just learning Swift.

import Foundation

class TaskManager{

    var taskDictArray = Dictionary<String, String>()

    init(){
        taskDictArray = [:]
    }

    func addTask(task: String, person: String){
        taskDictArray[task] = person
    }

}

var taskMgr = TaskManager()

taskMgr.addTask("take out trash", person: "emma")
taskMgr.addTask("wash dishes", person: "jack")
taskMgr.addTask("clean floor", person: "cleo")

//taskMgr.removeTaskByIndex(1)
//var a = taskMgr.getTaskByIndex(1)

Upvotes: 1

Views: 155

Answers (1)

Alex Zielenski
Alex Zielenski

Reputation: 3601

Dictionaries do not maintain their object order and the only way to get a value is using its key. You'll probably want to associate whatever list of tasks you have the index for with its corresponding key and use that manipulate the dictionary. This is the only way. You probably consider restructuring your application logic if it's impossible.

You'll need to add a function such as

func removeTask(task: String) {
     taskDictArray[task] = nil
}

So find a way to get the actual task string with which you are associating it.

Upvotes: 2

Related Questions