条件绑定的初始化程序必须具有可选类型,而不是“ Todo?.Type”

时间:2019-10-11 00:31:56

标签: swift optional

研究一个有点古老的教程,需要帮助弄清楚如何在没有可选类型的情况下进行初始化

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()
}
  

用于条件绑定的初始化程序必须具有可选类型,而不是'Todo?.Type'

继续收到此错误消息

1 个答案:

答案 0 :(得分:0)

您需要通过execute-batch!初始化todo。您也可以通过var todo = Todo(parameter1Name: Parameter1Type, parameter2Name: Parameter2Type)声明Todo的可选实例,或者通过var todo: Todo?隐式解包可选,然后再设置此值。可以在此处了解可选类型:What does an exclamation mark mean in the Swift language?

var todo: Todo!