0

Working on a tutorial thats a little old and need help figuring out how to initialize without optional types

var resultsController: NSFetchedResultsController<Todo>!
let coreDataStack = CoreDataStack()



override func viewDidLoad() {
    super.viewDidLoad()
    //Request
    let request: NSFetchRequest<Todo> = Todo.fetchRequest()
    let sortDesriptors = NSSortDescriptor(key: "date", ascending: true)

    //Init
    request.sortDescriptors = [sortDesriptors]
    resultsController = NSFetchedResultsController(
        fetchRequest: request,
        managedObjectContext: coreDataStack.managedContext,
        sectionNameKeyPath: nil,
        cacheName: nil)

    resultsController.delegate = self
    //Fetch
    do {
        try resultsController.performFetch()
    } catch {
        print("Perfom fetch error: \(error)")
    }


}


var managedContext: NSManagedObjectContext!
var todo = Todo?

if let todo = todo {                 <--- same issue here
    textView.text = todo.title
    textView.text = todo.title
    segmentedControl.selectedSegmentIndex = Int(todo.priority)




if let todo = todo {                 //<-- need help here.
    todo.title = title
    todo.priority = Int16(segmentedControl.selectedSegmentIndex)
} else {
    let todo = Todo(context: managedContext)
    todo.title = title
    todo.priority = Int16(segmentedControl.selectedSegmentIndex)
    todo.date = Date()
}

Initializer for conditional binding must have Optional type, not 'Todo?.Type'

keep getting this error message

chris p
  • 1
  • 1

1 Answers1

0

You either need to initialize todo via var todo = Todo(parameter1Name: Parameter1Type, parameter2Name: Parameter2Type). You could also declare an optional instance of Todo via var todo: Todo? or implicitly unwrapped optional via var todo: Todo! and set this value later. Optional types can be understood here: What does an exclamation mark mean in the Swift language?

var managedContext: NSManagedObjectContext!

//Option 1:
var todo = Todo()

//Option 2:
var optionalTodo: Todo?

optionalTodo = Todo()

if let todo = todo {
    textView.text = todo.title
    textView.text = todo.title
    segmentedControl.selectedSegmentIndex = Int(todo.priority)
    todo.title = title
    todo.priority = Int16(segmentedControl.selectedSegmentIndex)
} else {
    let todo = Todo(context: managedContext)
    todo.title = title
    todo.priority = Int16(segmentedControl.selectedSegmentIndex)
    todo.date = Date()
}
David Chopin
  • 2,780
  • 2
  • 19
  • 40
  • Also note that in the `else`, you probably don't want the `let`. That creates yet another variable named `todo` and it does not set the `todo` property. – rmaddy Oct 11 '19 at 02:29
  • Good call, I hadn’t looked much at what was inside the conditionals – David Chopin Oct 11 '19 at 03:08