简体   繁体   English

将ivar传递给Swift方法

[英]Passing in ivar into method Swift

I am making a simple reminder app in Swift and I'm having a hard time figuring out why I can't get my method to compile. 我正在用Swift开发一个简单的提醒应用程序,并且很难弄清楚为什么我无法编译我的方法。

 for reminder in self.reminders {

            if dates.contains(dateFormatter.stringFromDate(reminder.date)) {
                dates.add(reminderDate)
            }

}

On the call to stringFromDate I am getting an error saying 在对stringFromDate的调用上,我收到一条错误消息,说

"Cannot invoke "stringFromDate" with an argument list of type (NSDate?!)" “无法使用类型为(NSDate ?!)的参数列表调用“ stringFromDate””

The date ivar is an NSDate, what do I need to be able to call it? date ivar是NSDate,我需要什么才能调用它?

I declare the property as var date: NSDate 我将该属性声明为var date: NSDate

Declaration for the property var reminders = [] 声明属性var reminders = []

class TRReminder {

        enum TRPriority {
            case Low, Medium, High
        }

        var title: String
        var date: NSDate
        var location: String
        var priority: TRPriority
        var note: String


        init(title: String, date: NSDate, location: String, priority: TRPriority, note: String) {

            self.title = title
            self.date = date
            self.location = location
            self.priority = priority
            self.note = note

        }

    }

Do this 做这个

var reminders = [TRReminder]()

Declaring it as [] is, I believe, equivalent to [AnyObject?] 我认为将其声明为[]等效于[AnyObject?]

Sometimes it's best to break up the method a bit more to see where any potential loop holes are here, try replacing your implementation with this on run through the output to see if you're missing anything: 有时最好将方法进一步分解,以查看此处可能存在的任何漏洞,然后尝试在运行输出时用此方法替换实现,以查看是否遗漏了什么:

for reminder in self.reminders {
    println("\(reminder)") //sanity check
    if let date = reminder.date {
        if let formattedDate = dateFormatter.stringFromDate(date) {
            if dates.contains(formattedDate) { 
                dates.add(reminderDate) //the logic here seems a bit confusing? where does reminderDate come from?
            }
        } else {
            println("oops") //yet another sanity check
        }
    } else {
        println("something went wrong here") // another sanity check
    }
}

This will surely not fix your problem but it might help you get on track to see where a mistake was made. 这肯定不会解决您的问题,但可能会帮助您按计划查看错误出处。

Hope this helps! 希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM