Swift 将不同的类型传递到函数中
我试图根据不同的核心数据对象希望保存到的列表将其保存到不同的核心数据对象 是否有可能生成一个传入类型的函数,并在此基础上保存到正确的列表中Swift 将不同的类型传递到函数中,swift,function,core-data,types,Swift,Function,Core Data,Types,我试图根据不同的核心数据对象希望保存到的列表将其保存到不同的核心数据对象 是否有可能生成一个传入类型的函数,并在此基础上保存到正确的列表中 let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext if index == 0 { let task = TodayTask(context: context) task.name
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
if index == 0 {
let task = TodayTask(context: context)
task.name = taskText.text! // Do this in function insead
task.adress = addressField.text // Do this in function insead
task.date = userDate // Do this in function insead
}else if listIndex.selectedSegmentIndex == 1 {
let task = WeekTask(context: context)
task.name = taskText.text!
}else {
let task = Task(context: context)
task.name = taskText.text!
func saveToCoreData(task: SomeList){
let task = SomeList(context: context) // The correct list based on what the user chooses
task.name = taskText.text!
task.adress = addressField.text
task.date = userDate
}
您应该使用一种称为动态分派的技术。例如:
func accept(value: String) {
//This to process a string
}
func accept(value: Int){
//This called to process an Int
}
然后您只需调用accept(value:myValue),函数就会动态地分派给正确的函数 我尝试了你所说的,但我似乎没有让它工作,我得到一个错误无法转换类型TodayStask.type的值到Expected参数类型TodayStask别介意我重写了函数,现在它工作了!谢谢