T. Benjamin Larsen
T. Benjamin Larsen

Reputation: 6393

Why am I allowed to call instance methods on a class?

After receiving help with a question yesterday I'm still not able to quite wrap my head around this, or why the following is allowed:

let string = NSString.hasPrefix("aString")

To me this looks like I'm simply calling a instance method straight from a Class. In the above example it doesn't particularly make sense, but it is obviously allowed as it both compiles without warnings and runs without any errors.

Any help to eradicate this particular part of my (vast) ignorance in regards to Swift would be highly appreciated.


Edit: Is this perhaps because there are nothing separating class and instance-methods in Swift and its a way to handle this discrepancy between Objective-C and Swift?

Upvotes: 4

Views: 159

Answers (1)

Lukas
Lukas

Reputation: 3133

To me, it looks like instance methods are basically curried class methods that take the instance as a first argument:

import Foundation

let string = NSString(string:"foobar")

string.hasPrefix("foo") // => true
NSString.hasPrefix(string)("foo") // => true

So basically, writing cls.method(instance) seems to be the same as writing instance.method (note that methods are closures, you can assign them to variables and call those later):

let f1 = string.hasPrefix
let f2 = NSString.hasPrefix(string)

f1("f") // => true
f1("foob") // => true
f1("nope") // => false

f2("f") // => true
f2("foob") // => true
f2("nope") // => false

Note: This is how it behaves and what I would find logical (and Python works similarly, for example). I don't know if this is actually true.

Upvotes: 3

Related Questions