【问题标题】:Missing argument for parameter #1 in call error for function with no params. Swift没有参数的函数的调用错误中参数 #1 的参数丢失。迅速
【发布时间】:2014-10-15 15:40:41
【问题描述】:

我正在使用 xcode 6 beta 6,但对于没有参数的函数,我收到了这个奇怪的错误。

这里是函数

func allStudents ()-> [String]{
    var appDel:AppDelegate = (UIApplication.sharedApplication().delegate as AppDelegate)
    var context:NSManagedObjectContext = appDel.managedObjectContext!
    var request = NSFetchRequest(entityName: "Student")
    request.returnsObjectsAsFaults = false
    //Set error to nil for now
    //TODO: Give an actual error.
    var result:NSArray = context.executeFetchRequest(request, error: nil)

    var students:[String]!
    for child in result{
        var fullname:String = child.valueForKey("firstName") as String + " "
        fullname += child.valueForKey("middleName") as String + " "
        fullname += child.valueForKey("lastName") as String
        students.append(fullname)
    }


    return students
}

这是电话

var all = StudentList.allStudents()

这是一个错误还是我在这里做错了什么?

【问题讨论】:

  • 什么是StudentList?是你的类还是变量(在这种情况下它应该有一个小写的 s - studentList)
  • 你确定那是它崩溃的那条线吗?在操场上的一个简单版本可以正常工作。虽然你确实有一个明显的错误:var students:[String]! 永远不会得到一个值,它被初始化为nil。你可能想要var students:[String] = []。
  • 这不是程序崩溃的错误,它的 xcode 告诉我它错了。是的,StudentList 是我的班级。

标签: ios swift xcode6-beta6


【解决方案1】:

假设StudentList 是一个类,即

class StudentList {

    func allStudents ()-> [String]{
      ....
    }
}

然后是这样的表达式

var all = StudentList.allStudents() 

将抛出上述异常,因为allStudents 应用于类而不是类的实例。 allStudents 函数需要一个 self 参数(对实例的引用)。它解释了错误消息。

如果你这样做,这将得到解决

var all = StudentList().allStudents()

【讨论】:

  • 或者它需要是类/静态方法
【解决方案2】:

Swift 有实例方法和类型方法。实例方法是从类的特定实例调用的方法。类型方法是从类本身调用的静态方法。

实例方法

实例方法如下所示:

class StudentList {

    func allStudents() -> [String] {
      ....
    }
}

为了调用allStudents方法,需要先初始化StudentsList类。

let list = StudentsList() // initialize the class
let all = list.allStudents() // call a method on the class instance

尝试调用类本身的实例方法会出错。

类型方法

Type Methods 是属于类的静态方法,而不是类的实例。正如在@AnthodyKong 的答案中提到的那样,可以通过在func 之前使用class 或static 关键字来创建类型方法。类通过引用传递,结构体通过值传递,所以它们被称为引用类型和值类型。以下是它们的外观:

参考类型

class StudentList {

    class func allStudents() -> [String] {
      ....
    }
}

值类型

struct StudentList {

    static func allStudents() -> [String] {
      ....
    }
}

打电话给

let all = StudentList.allStudents()

因为allStudents是一个类型方法,所以类(或结构)不需要先初始化。

另请参阅

【讨论】:

  • 这很好,但他们确实需要更新您收到的警告文本。为什么不只是说该函数应该是一个类函数并提供为您修复它...?
  • 确实如此。如果有人发明了一种能够提供智能错误消息的编程语言,我正在学习它。
  • 我们为 clang 编写一个 API 怎么样,在它向您显示错误消息之前,它首先搜索堆栈溢出并使用机器学习算法找到问题最可能的解决方案,然后提供你是问题的链接:D
猜你喜欢
  • 2016-04-11
  • 1970-01-01
  • 2021-03-06
  • 1970-01-01
  • 2023-03-25
  • 1970-01-01
  • 1970-01-01
  • 2015-01-15
  • 1970-01-01
相关资源
最近更新 更多