There is a very interesting way of writing in Swift, which allows us to invoke the method on this instance without using the instance directly, but to take out the signature of an instance method of that type by type, and then pass the instance to get the method that actually needs to be invoked. For example, we have this definition:
Copy Code code as follows:
Class MyClass {
Func method (Number:int)-> Int {
Return number + 1
}
}
The most common way to invoke method methods is to generate an instance of MyClass, and then invoke it using. Method:
Copy Code code as follows:
Let object = MyClass ()
Let result = Object.Method (1)
result = 2
This limits our ability to determine the object instance and the corresponding method invocation only at compile time. In fact, we can also use the method we have just mentioned to rewrite the above example as follows:
Copy Code code as follows:
Let F = Myclass.method
Let object = MyClass ()
Let result = f (object) (1)
This syntax may seem strange, but it's not really complicated. Swift can use Type.instancemethod syntax directly to generate a method that can be gerty. If we look at the type of f (Alt + click), you know that it is:
Copy Code code as follows:
In fact, for type.instancemethod such a value statement, actually just
Copy Code code as follows:
The thing to do is like the following literal conversions:
Copy Code code as follows:
Let F = {(Obj:myclass) in Obj.method}
It is not difficult to understand why the above method of invocation can be set up.
This method applies only to instance methods, which cannot be written in a similar way for getter or setter of attributes. In addition, if we encounter a name conflict with a type method:
Copy Code code as follows:
Class MyClass {
Func method (Number:int)-> Int {
Return number + 1
}
Class Func Method (Number:int)-> Int {
return number
}
}
If you do not change, Myclass.method will take the type method, and if we want to take the instance method, we can explicitly add the type declaration to differentiate. This is not only effective here, but it is a good way to solve the problem when most of the other names are ambiguous:
Copy Code code as follows:
Let F1 = Myclass.method
Version of Class Func method
Let f2:int-> Int = Myclass.method
Same as F1.
Let f3:myclass-> int-> int = Myclass.method
Func version of method