Why am I allowed to call class instance methods?

After getting help yesterday, I still can’t completely wrap my question around myself or why the following is allowed:

let string = NSString.hasPrefix("aString")

It seems to me that I'm just calling the instance method directly from the class. In the above example, this does not make much sense, but obviously this is allowed, since it compiles without warning and starts without any errors.

Any help in eradicating this part of my (vast) ignorance regarding Swift would be greatly appreciated.


Edit: Perhaps this is because there is nothing in Swift to separate the class and instance methods and the way to deal with this mismatch between Objective-C and Swift?

+4
source share
1

, curried , :

import Foundation

let string = NSString(string:"foobar")

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

, cls.method(instance) , instance.method ( , - , ):

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

. ( Python , ). , .

+3

Source: https://habr.com/ru/post/1543747/


All Articles