Hacker News new | ask | show | jobs
by kennywinker 4400 days ago
Method parameter names are used similarly in Swift as in ObjC. For example two methods can have the same name, as long as they have a difference set of parameters. For example:

    func methodName(paramName: String)
and

    func methodName(paramName: String, otherParam: Int)
are different.

I'm still playing with this but there are some interesting/weird things in here. What follows is a bunch of random observations of how named params work in Swift / ObjC. For instance:

    func methodName(name name: String)
Can be shortened using a pound symbol, because the variable name within the method, and the parameter name are the same thing:

    func methodName(#name: String)
It also seems that most of the Cocoa APIs follow a convention, when called from Swift, of having an unnamed first parameter, and a named second parameter. e.g. this:

    -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
becomes:

    func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell!
which means it's called like so:

    myObject.tableView(tableView, cellForRowAtIndexPath: indexPath)
If you name a parameter, you have to use the name. The order of parameters matters, and there doesn't seem to be a way to define optional method parameters (make sense as parameter names are essentially ObjC "selectors").
1 comments

> and there doesn't seem to be a way to define optional method parameters

Did you miss the part about default values?

If you're calling an Objective-C selector with more than one argument, you are indeed using an external parameter name, but external parameters are explicitly not required if you're writing pure Swift.

https://developer.apple.com/library/prerelease/ios/documenta...

Oh cool, I definitely missed that!