gpt4 book ai didi

swift - 条件绑定(bind)的初始化程序必须具有可选类型,而不是 'Todo?.Type'

转载 作者:行者123 更新时间:2023-11-30 10:34:40 25 4
gpt4 key购买 nike

正在编写一个有点旧的教程,需要帮助弄清楚如何在没有可选类型的情况下进行初始化

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'

不断收到此错误消息

最佳答案

您需要通过 var todo = Todo(parameter1Name: Parameter1Type,parameter2Name: Parameter2Type) 初始化 todo。您还可以通过 var todo: Todo? 声明 Todo 的可选实例,或通过 var todo: Todo! 隐式解包可选实例并设置此值之后。可选类型可以在这里理解: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()
}

关于swift - 条件绑定(bind)的初始化程序必须具有可选类型,而不是 'Todo?.Type',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58332737/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com