0

I have created a class as such:

 class Task {
        var name:String
        var description:String
        var date:NSDate
        var taskCompleted:Bool

        init(name:String, description:String,date:NSDate, taskCompleted:Bool){
            self.name = name
            self.description = description
            self.date = date
            self.taskCompleted = taskCompleted
        }
    }

I then create a new object like so:

let newTask:AnyObject = Task(name: taskName.text!, description: descriptionInput.text, date: datePicker.date, taskCompleted: false)

Later on I add the object to an array:

var tasks = [AnyObject]()
tasks.append(newTask)

However, when I try to access the object again like so I get an error:

print(tasks[0].name)

ERROR: unexpectedly found nil while unwrapping an Optional value

1
  • 1
    Why AnyObject? Just use Task Commented Jan 26, 2016 at 22:55

3 Answers 3

2

Your array is of type [AnyObject]. If you want to avoid using as keyword, you should make it of type [Task] because AnyObject doesn't necesseraly have a name property. This is why it yells found nil while unwrapping an Optional value.

Try this :

let newTask:Task = Task(name: taskName.text!, description: descriptionInput.text, date: datePicker.date, taskCompleted: false)

var tasks = [Task]()
tasks.append(newTask)

print(tasks[0].name)

Like Lindsey said, you can use the as keyword if you want to have different types of objects in it but I don't think that is what you want.

Sign up to request clarification or add additional context in comments.

Comments

2

In your current code tasks[0] is of type AnyObject which does not have a "name" property. Try changing:

print(tasks[0].name)

to

print((tasks[0] as! Task).name)

in order to change tasks[0] from AnyObject to Task.

1 Comment

Thanks for the input!
2

Currently when you access a task from your array you get back an AnyObject which knows nothing about your name attribute.

You can do one of two things depending on what you are trying to accomplish

  1. You can set your array to be of type [Task] not AnyObject.
  2. Cast the AnyObject to Task when retrieving it from array. (task[0] as! Task).name

1 Comment

Thanks for the input!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.