Missing argument for parameter #1 in call error for function with no params. Swift

Boid picture Boid · Aug 21, 2014 · Viewed 25.4k times · Source

I am using xcode 6 beta 6 and I get this weird error for a function that has no params.

Here is the 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
}

and here is the call

var all = StudentList.allStudents()

Is this a bug or am I doing something wrong here?

Answer

Anthony Kong picture Anthony Kong · Aug 22, 2014

Assuming StudentList is a class, i.e.

class StudentList {

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

Then an expression like this

var all = StudentList.allStudents() 

will throw the said exception, because allStudents is applied to a class instead of an instance of the class. The allStudents function is expecting a self parameter (a reference to the instance). It explains the error message.

This will be resolved if you do

var all = StudentList().allStudents()