没有参数的函数在调用错误中缺less参数#1的参数。 迅速

我正在使用xcode 6testing版6,我得到这个奇怪的错误,没有参数的函数。

这是function

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是一个类,即

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

然后像这样的expression

 var all = StudentList.allStudents() 

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

如果你这样做会得到解决

 var all = StudentList().allStudents() 

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

实例方法

一个实例方法看起来像这样:

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

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

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

尝试调用类本身的实例方法会产生错误。

types方法

types方法是属于类的静态方法,而不是类的实例。 正如在@ Anthodykong的回答中所暗示的那样,可以通过在func之前使用classstatic关键字来创buildtypes方法。 类是通过引用传递的,Struct是通过值传递的,所以这些被称为引用types和值types。 以下是他们的样子:

参考types

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

值types

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

打电话

 let all = StudentList.allStudents() 

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

也可以看看

  • 方法文件
  • Swift中的实例方法和types方法