【问题标题】:Pass different types into function将不同类型传递给函数
【发布时间】:2018-01-02 23:31:18
【问题描述】:

我正在尝试根据他们想要保存到的列表来保存到不同的核心数据对象。

是否可以制作一个您传入类型的函数并根据该类型保存到正确的列表中?

 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
}

【问题讨论】:

    标签: swift function core-data types


    【解决方案1】:

    您应该使用一种称为动态调度的技术。例如:

    func accept(value: String) {
        //This to process a string
    }
    
    func accept(value: Int){
        //This called to process an Int
    }
    

    然后您只需调用 accept(value: myValue) ,该函数就会动态分派给正确的函数。

    【讨论】:

    • 我试过你说的,但我似乎没有让它工作,我收到一个错误无法将 TodayTask.Type 类型的值转换为预期的参数类型 TodayTask
    • 没关系,我重写了函数,现在它可以工作了!谢谢!
    猜你喜欢
    • 2016-02-28
    • 2020-02-06
    • 1970-01-01
    • 2017-05-10
    • 1970-01-01
    • 1970-01-01
    • 2012-10-27
    • 2014-12-15
    • 1970-01-01
    相关资源
    最近更新 更多