从自定义 class 调用方法而不创建新实例,使用 Int 参数的 IntegerLiterallConvertible 错误

Call method from custom class without creating new instance, IntegerLiterallConvertible error with Int argument

我试图在不创建新实例的情况下调用 class 方法。我很确定方法调用是正确的。我创建了一个名为 CalculateWeek 的 class。这个 class 有几种方法可以对日期进行操作。这是我的 CalculateWeek class `

    import Foundation
    class CalculateWeek {
    let calendar = NSCalendar.currentCalendar()
    var date = NSDate()

    func weekStart(weekDaySelected:Int)->NSDate?{
        //Get Current Weekday
        let currentWeekday = calendar.components(.CalendarUnitWeekday, fromDate:date)
        var weekDay = [currentWeekday.weekday]  //date component
        println("Current weekday is \(weekDay[0])") //

        var daysToSubtract = 1
        let dateComponents = NSDateComponents()
        dateComponents.day = daysToSubtract

        let startDate = calendar.dateByAddingComponents(dateComponents, toDate: todayStart!, options: nil)  
        return startDate  
    }

然后我尝试从我的视图控制器调用这个方法 Class :

var tempWeekEnd = CalculateWeek.weekStart(1)

我收到错误消息“Type CalculateWeek' does not conform to protocol 'IntegerLiteralConvertible' 我知道代码是正确的,因为如果我将方法 weekStart 复制并粘贴到我的视图控制器 class 中,它就可以正常工作。它一定与我调用方法的方式有关,但我无法弄清楚。在该方法中,我的参数类型是 Int,我正在发送一个 Int。

为什么不先创建一个对象(也许是私有属性)然后再使用它?不创建任何实例是不可能的,var tempWeekEnd = CalculateWeek().weekStart(1) 有效,因此您需要创建一个实例。

private var cw = CalculateWeek()
...
var tempWeekEnd = cw.weekStart(1)

希望对您有所帮助

我发现代码中有几个问题:

  1. weekStart()方法不是class方法,所以不能按你想的方式调用。你需要实例来调用它。

  2. 您正在操作的日期是一个实例成员,如果您使用 class 方法将无法从 weekStart() 访问它。

我建议您在创建的 CalculateWeek 实例上调用 weekStart() 或使其成为 class 方法以按您想要的方式调用。

在相关说明中,我请求您查看我的日期操作框架 here。它有很多你可能想要的包装器。